Konteks Web Spring

1. Pengenalan

Semasa menggunakan Spring dalam aplikasi web, kami mempunyai beberapa pilihan untuk mengatur konteks aplikasi yang menghubungkan semuanya.

Dalam artikel ini, kami akan menganalisis dan menerangkan pilihan paling umum yang ditawarkan oleh Spring.

2. Konteks Aplikasi Web Root

Setiap webapp Spring mempunyai konteks aplikasi yang berkaitan dengan kitaran hayatnya: konteks aplikasi web root.

Ini adalah ciri lama yang mendahului Spring Web MVC, jadi tidak terikat secara khusus dengan teknologi kerangka web apa pun.

Konteks dimulakan ketika aplikasi dimulakan, dan dimusnahkan ketika berhenti, terima kasih kepada pendengar konteks servlet. Jenis konteks yang paling umum juga dapat disegarkan pada waktu berjalan, walaupun tidak semua implementasi ApplicationContext memiliki kemampuan ini.

Konteks dalam aplikasi web selalu merupakan contoh WebApplicationContext . Itulah antara muka yang meluaskan ApplicationContext dengan kontrak untuk mengakses ServletContext .

Bagaimanapun, aplikasi biasanya tidak perlu memperhatikan perincian pelaksanaannya: konteks aplikasi web root hanyalah tempat terpusat untuk menentukan kacang bersama.

2.1. The ContextLoaderListener

Konteks aplikasi root web yang dijelaskan di bahagian sebelumnya dikendalikan oleh pendengar org.springframework.web.context.ContextLoaderListener kelas , yang merupakan sebahagian daripada modul web spring .

Secara lalai, pendengar akan memuat konteks aplikasi XML dari /WEB-INF/applicationContext.xml . Walau bagaimanapun, lalai tersebut boleh diubah. Kita boleh menggunakan anotasi Java dan bukan XML, misalnya.

Kita boleh mengkonfigurasi pendengar ini sama ada dalam deskriptor webapp ( fail web.xml ) atau secara terprogram dalam lingkungan Servlet 3.x.

Pada bahagian berikut, kita akan melihat setiap pilihan ini secara terperinci.

2.2. Menggunakan web.xml dan Konteks Aplikasi XML

Semasa menggunakan web.xml , kami mengkonfigurasi pendengar seperti biasa:

  org.springframework.web.context.ContextLoaderListener  

Kita dapat menentukan lokasi alternatif konfigurasi konteks XML dengan parameter konteksConfigLocation :

 contextConfigLocation /WEB-INF/rootApplicationContext.xml 

Atau lebih daripada satu lokasi, dipisahkan dengan koma:

 contextConfigLocation /WEB-INF/context1.xml, /WEB-INF/context2.xml 

Kita juga boleh menggunakan corak:

 contextConfigLocation /WEB-INF/*-context.xml 

Walau bagaimanapun, hanya satu konteks yang ditentukan, dengan menggabungkan semua definisi kacang yang dimuat dari lokasi yang ditentukan.

2.3. Menggunakan web.xml dan Konteks Aplikasi Java

Kami juga dapat menentukan jenis konteks lain selain daripada yang berasaskan XML lalai. Sebagai contoh, mari kita lihat bagaimana menggunakan konfigurasi anotasi Java.

Kami menggunakan parameter contextClass untuk memberitahu pendengar jenis konteks yang hendak dibuat:

 contextClass  org.springframework.web.context.support.AnnotationConfigWebApplicationContext  

Setiap jenis konteks mungkin mempunyai lokasi konfigurasi lalai. Dalam kes kami, AnnotationConfigWebApplicationContext tidak memilikinya, jadi kami harus menyediakannya.

Oleh itu, kami dapat menyenaraikan satu atau lebih kelas yang diberi anotasi:

 contextConfigLocation  com.baeldung.contexts.config.RootApplicationConfig, com.baeldung.contexts.config.NormalWebAppConfig  

Atau kita boleh mengetahui konteksnya untuk mengimbas satu atau lebih pakej:

 contextConfigLocation com.baeldung.bean.config 

Dan, tentu saja, kita boleh mencampurkan dan memadankan dua pilihan.

2.4. Konfigurasi Terprogram Dengan Servlet 3.x

Versi 3 dari Servlet API telah membuat konfigurasi melalui fail web.xml menjadi pilihan sepenuhnya. Perpustakaan dapat menyediakan serpihan web mereka, yang merupakan konfigurasi XML yang dapat mendaftarkan pendengar, penapis, servlet dan sebagainya.

Juga, pengguna memiliki akses ke API yang memungkinkan untuk menentukan secara teratur setiap elemen aplikasi berbasis servlet.

The bunga-web jenama modul menggunakan ciri-ciri ini dan menawarkan API untuk mendaftar komponen aplikasi apabila ia bermula.

Spring scans the application's classpath for instances of the org.springframework.web.WebApplicationInitializer class. This is an interface with a single method, void onStartup(ServletContext servletContext) throws ServletException, that's invoked upon application startup.

Let's now look at how we can use this facility to create the same types of root web application contexts that we've seen earlier.

2.5. Using Servlet 3.x and an XML Application Context

Let's start with an XML context, just like in Section 2.2.

We'll implement the aforementioned onStartup method:

public class ApplicationInitializer implements WebApplicationInitializer { @Override public void onStartup(ServletContext servletContext) throws ServletException { //... } }

Let's break the implementation down line by line.

We first create a root context. Since we want to use XML, it has to be an XML-based application context, and since we're in a web environment, it has to implement WebApplicationContext as well.

The first line, thus, is the explicit version of the contextClass parameter that we've encountered earlier, with which we decide which specific context implementation to use:

XmlWebApplicationContext rootContext = new XmlWebApplicationContext();

Then, in the second line, we tell the context where to load its bean definitions from. Again, setConfigLocations is the programmatic analogous of the contextConfigLocation parameter in web.xml:

rootContext.setConfigLocations("/WEB-INF/rootApplicationContext.xml");

Finally, we create a ContextLoaderListener with the root context and register it with the servlet container. As we can see, ContextLoaderListener has an appropriate constructor that takes a WebApplicationContext and makes it available to the application:

servletContext.addListener(new ContextLoaderListener(rootContext));

2.6. Using Servlet 3.x and a Java Application Context

If we want to use an annotation-based context, we could change the code snippet in the previous section to make it instantiate an AnnotationConfigWebApplicationContext instead.

However, let's see a more specialized approach to obtain the same result.

The WebApplicationInitializer class that we've seen earlier is a general-purpose interface. It turns out that Spring provides a few more specific implementations, including an abstract class called AbstractContextLoaderInitializer.

Its job, as the name implies, is to create a ContextLoaderListener and register it with the servlet container.

We only have to tell it how to build the root context:

public class AnnotationsBasedApplicationInitializer extends AbstractContextLoaderInitializer { @Override protected WebApplicationContext createRootApplicationContext() { AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); rootContext.register(RootApplicationConfig.class); return rootContext; } }

Here we can see that we no longer need to register the ContextLoaderListener, which saves us from a little bit of boilerplate code.

Note also the use of the register method that is specific to AnnotationConfigWebApplicationContext instead of the more generic setConfigLocations: by invoking it, we can register individual @Configuration annotated classes with the context, thus avoiding package scanning.

3. Dispatcher Servlet Contexts

Let's now focus on another type of application context. This time, we'll be referring to a feature which is specific to Spring MVC, rather than part of Spring's generic web application support.

Spring MVC applications have at least one Dispatcher Servlet configured (but possibly more than one, we'll talk about that case later). This is the servlet that receives incoming requests, dispatches them to the appropriate controller method, and returns the view.

Each DispatcherServlet has an associated application context. Beans defined in such contexts configure the servlet and define MVC objects like controllers and view resolvers.

Let's see how to configure the servlet's context first. We'll look at some in-depth details later.

3.1. Using web.xml and an XML Application Context

DispatcherServlet is typically declared in web.xml with a name and a mapping:

 normal-webapp  org.springframework.web.servlet.DispatcherServlet  1   normal-webapp /api/* 

If not otherwise specified, the name of the servlet is used to determine the XML file to load. In our example, we'll use the file WEB-INF/normal-webapp-servlet.xml.

We can also specify one or more paths to XML files, in a similar fashion to ContextLoaderListener:

 ...  contextConfigLocation /WEB-INF/normal/*.xml  

3.2. Using web.xml and a Java Application Context

When we want to use a different type of context we proceed like with ContextLoaderListener, again. That is, we specify a contextClass parameter along with a suitable contextConfigLocation:

 normal-webapp-annotations  org.springframework.web.servlet.DispatcherServlet   contextClass  org.springframework.web.context.support.AnnotationConfigWebApplicationContext    contextConfigLocation com.baeldung.contexts.config.NormalWebAppConfig  1 

3.3. Using Servlet 3.x and an XML Application Context

Again, we'll look at two different methods for programmatically declaring a DispatcherServlet, and we'll apply one to an XML context and the other to a Java context.

So, let's start with a generic WebApplicationInitializer and an XML application context.

As we've seen previously, we have to implement the onStartup method. However, this time we'll create and register a dispatcher servlet, too:

XmlWebApplicationContext normalWebAppContext = new XmlWebApplicationContext(); normalWebAppContext.setConfigLocation("/WEB-INF/normal-webapp-servlet.xml"); ServletRegistration.Dynamic normal = servletContext.addServlet("normal-webapp", new DispatcherServlet(normalWebAppContext)); normal.setLoadOnStartup(1); normal.addMapping("/api/*");

We can easily draw a parallel between the above code and the equivalent web.xml configuration elements.

3.4. Using Servlet 3.x and a Java Application Context

This time, we'll configure an annotations-based context using a specialized implementation of WebApplicationInitializer: AbstractDispatcherServletInitializer.

That's an abstract class that, besides creating a root web application context as previously seen, allows us to register one dispatcher servlet with minimum boilerplate:

@Override protected WebApplicationContext createServletApplicationContext() { AnnotationConfigWebApplicationContext secureWebAppContext = new AnnotationConfigWebApplicationContext(); secureWebAppContext.register(SecureWebAppConfig.class); return secureWebAppContext; } @Override protected String[] getServletMappings() { return new String[] { "/s/api/*" }; }

Here we can see a method for creating the context associated with the servlet, exactly like we've seen before for the root context. Also, we have a method to specify the servlet's mappings, as in web.xml.

4. Parent and Child Contexts

So far, we've seen two major types of contexts: the root web application context and the dispatcher servlet contexts. Then, we might have a question: are those contexts related?

It turns out that yes, they are. In fact, the root context is the parent of every dispatcher servlet context. Thus, beans defined in the root web application context are visible to each dispatcher servlet context, but not vice versa.

So, typically, the root context is used to define service beans, while the dispatcher context contains those beans that are specifically related to MVC.

Note that we've also seen ways to create the dispatcher servlet context programmatically. If we manually set its parent, then Spring does not override our decision, and this section no longer applies.

In simpler MVC applications, it's sufficient to have a single context associated to the only one dispatcher servlet. There's no need for overly complex solutions!

Still, the parent-child relationship becomes useful when we have multiple dispatcher servlets configured. But when should we bother to have more than one?

In general, we declare multiple dispatcher servlets when we need multiple sets of MVC configuration. For example, we may have a REST API alongside a traditional MVC application or an unsecured and a secure section of a website:

Note: when we extend AbstractDispatcherServletInitializer (see section 3.4), we register both a root web application context and a single dispatcher servlet.

So, if we want more than one servlet, we need multiple AbstractDispatcherServletInitializer implementations. However, we can only define one root context, or the application won't start.

Fortunately, the createRootApplicationContext method can return null. Thus, we can have one AbstractContextLoaderInitializer and many AbstractDispatcherServletInitializer implementations that don't create a root context. In such a scenario, it is advisable to order the initializers with @Order explicitly.

Also, note that AbstractDispatcherServletInitializer registers the servlet under a given name (dispatcher) and, of course, we cannot have multiple servlets with the same name. So, we need to override getServletName:

@Override protected String getServletName() { return "another-dispatcher"; }

5. A Parent and Child Context Example

Suppose that we have two areas of our application, for example a public one which is world accessible and a secured one, with different MVC configurations. Here, we'll just define two controllers that output a different message.

Also, suppose that some of the controllers need a service that holds significant resources; a ubiquitous case is persistence. Then, we'll want to instantiate that service only once, to avoid doubling its resource usage, and because we believe in the Don't Repeat Yourself principle!

Let's now proceed with the example.

5.1. The Shared Service

In our hello world example, we settled for a simpler greeter service instead of persistence:

package com.baeldung.contexts.services; @Service public class GreeterService { @Resource private Greeting greeting; public String greet() { return greeting.getMessage(); } }

We'll declare the service in the root web application context, using component scanning:

@Configuration @ComponentScan(basePackages = { "com.baeldung.contexts.services" }) public class RootApplicationConfig { //... }

We might prefer XML instead:

5.2. The Controllers

Let's define two simple controllers which use the service and output a greeting:

package com.baeldung.contexts.normal; @Controller public class HelloWorldController { @Autowired private GreeterService greeterService; @RequestMapping(path = "/welcome") public ModelAndView helloWorld() { String message = "

Normal " + greeterService.greet() + "

"; return new ModelAndView("welcome", "message", message); } } //"Secure" Controller package com.baeldung.contexts.secure; String message = "

Secure " + greeterService.greet() + "

";

As we can see, the controllers lie in two different packages and print different messages: one says “normal”, the other “secure”.

5.3. The Dispatcher Servlet Contexts

As we said earlier, we're going to have two different dispatcher servlet contexts, one for each controller. So, let's define them, in Java:

//Normal context @Configuration @EnableWebMvc @ComponentScan(basePackages = { "com.baeldung.contexts.normal" }) public class NormalWebAppConfig implements WebMvcConfigurer { //... } //"Secure" context @Configuration @EnableWebMvc @ComponentScan(basePackages = { "com.baeldung.contexts.secure" }) public class SecureWebAppConfig implements WebMvcConfigurer { //... }

Or, if we prefer, in XML:

5.4. Putting It All Together

Now that we have all the pieces, we just need to tell Spring to wire them up. Recall that we need to load the root context and define the two dispatcher servlets. Although we've seen multiple ways to do that, we'll now focus on two scenarios, a Java one and an XML one. Let's start with Java.

We'll define an AbstractContextLoaderInitializer to load the root context:

@Override protected WebApplicationContext createRootApplicationContext() { AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); rootContext.register(RootApplicationConfig.class); return rootContext; } 

Then, we need to create the two servlets, thus we'll define two subclasses of AbstractDispatcherServletInitializer. First, the “normal” one:

@Override protected WebApplicationContext createServletApplicationContext() { AnnotationConfigWebApplicationContext normalWebAppContext = new AnnotationConfigWebApplicationContext(); normalWebAppContext.register(NormalWebAppConfig.class); return normalWebAppContext; } @Override protected String[] getServletMappings() { return new String[] { "/api/*" }; } @Override protected String getServletName() { return "normal-dispatcher"; } 

Then, the “secure” one, which loads a different context and is mapped to a different path:

@Override protected WebApplicationContext createServletApplicationContext() { AnnotationConfigWebApplicationContext secureWebAppContext = new AnnotationConfigWebApplicationContext(); secureWebAppContext.register(SecureWebAppConfig.class); return secureWebAppContext; } @Override protected String[] getServletMappings() { return new String[] { "/s/api/*" }; } @Override protected String getServletName() { return "secure-dispatcher"; }

And we're done! We've just applied what we touched in previous sections.

We can do the same with web.xml, again just by combining the pieces we've discussed so far.

Define a root application context:

  org.springframework.web.context.ContextLoaderListener   

A “normal” dispatcher context:

 normal-webapp  org.springframework.web.servlet.DispatcherServlet  1   normal-webapp /api/*  

And, finally, a “secure” context:

 secure-webapp  org.springframework.web.servlet.DispatcherServlet  1   secure-webapp /s/api/* 

6. Combining Multiple Contexts

There are other ways than parent-child to combine multiple configuration locations, to split big contexts and better separate different concerns. We've seen one example already: when we specify contextConfigLocation with multiple paths or packages, Spring builds a single context by combining all the bean definitions, as if they were written in a single XML file or Java class, in order.

However, we can achieve a similar effect with other means and even use different approaches together. Let's examine our options.

One possibility is component scanning, which we explain in another article.

6.1. Importing a Context Into Another

Alternatively, we can have a context definition import another one. Depending on the scenario, we have different kinds of imports.

Importing a @Configuration class in Java:

@Configuration @Import(SomeOtherConfiguration.class) public class Config { ... }

Loading some other type of resource, for example, an XML context definition, in Java:

@Configuration @ImportResource("classpath:basicConfigForPropertiesTwo.xml") public class Config { ... }

Finally, including an XML file in another one:

Thus, we have many ways to organize the services, components, controllers, etc., that collaborate to create our awesome application. And the nice thing is that IDEs understand them all!

7. Spring Boot Web Applications

Spring Boot automatically configures the components of the application, so, generally, there is less need to think about how to organize them.

Still, under the hood, Boot uses Spring features, including those that we've seen so far. Let's see a couple of noteworthy differences.

Spring Boot web applications running in an embedded container don't run any WebApplicationInitializer by design.

Should it be necessary, we can write the same logic in a SpringBootServletInitializer or a ServletContextInitializer instead, depending on the chosen deployment strategy.

However, for adding servlets, filters, and listeners as seen in this article, it is not necessary to do so. In fact, Spring Boot automatically registers every servlet-related bean to the container:

@Bean public Servlet myServlet() { ... }

The objects so defined are mapped according to conventions: filters are automatically mapped to /*, that is, to every request. If we register a single servlet, it is mapped to /, otherwise, each servlet is mapped to its bean name.

Sekiranya konvensyen di atas tidak berfungsi untuk kita, kita boleh menentukan FilterRegistrationBean , ServletRegistrationBean, atau ServletListenerRegistrationBean sebagai gantinya. Kelas-kelas tersebut membolehkan kami mengawal aspek pendaftaran yang baik.

8. Kesimpulan

Dalam artikel ini, kami telah memberikan pandangan mendalam mengenai pelbagai pilihan yang tersedia untuk menyusun dan mengatur aplikasi web Spring.

Kami telah meninggalkan beberapa ciri, terutama sokongan untuk konteks bersama dalam aplikasi perusahaan, yang, pada saat penulisan, masih belum ada pada Spring 5.

Pelaksanaan semua contoh dan potongan kod ini boleh didapati di projek GitHub.