Understanding Spring Web Initialization

Few years ago majority of us were used to write XML config files everywhere, to setup even simple Java EE application. Today using Java or Groovy to configure projects is becoming preferred way - you just need to take a look at Gradle or functionalities introduced in further versions of the Spring Framework to gen up on this.

Now I'll deal with configuring Spring contexts for web application.

Java EE provides ServletContainerInitializer interface, which allows libraries to be notified of a web application startup. Since Spring 3.1 we have SpringServletContainerInitializer class which handles WebApplicationInitializer by instantiating all found classes implementing this interface, sorting them basing on @Order annotation (non-annotated classes gets the highest possible order, so they are processed at the end) and invoking onStartup() method.


Spring since version 3.2 provides us a few classes implementing WebApplicationInitializer interface, from which first is AbstractContextLoaderInitializer. This class included in spring-web module uses abstract createRootApplicationContext() method to create application context, delegates it to ContextLoaderListener which then is being registered in the ServletContext instance. Creating application context using this class looks as follows:
public class SpringAnnotationWebInitializer
  extends AbstractContextLoaderInitializer {

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

}

That was the simplest way to start up Spring web context. But if we want to experience benefits provided by Spring MVC and don't want to manually register DispatcherServlet it'll be better to use another class: AbstractDispatcherServletInitializer. It extends previous class and adds two abstract methods: createServletApplicationContext() and getServletMappings().  First method returns WebApplicationContext that will be passed to DispatcherServlet, which will be automatically added into container ServletContext. Please notice that this context will be established as a child of the context returned by createRootApplicationContext() method. Second method - as you have probably already deduced - returns mappings that are used during servlet registration. You can also override getServletFilters() method if you need any custom filters, because default implementation returns just empty array. Exemplary implementation using this class could be:
public class SpringWebMvcInitializer
  extends AbstractDispatcherServletInitializer {

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

  @Override
  protected WebApplicationContext createServletApplicationContext() {
    AnnotationConfigWebApplicationContext applicationContext =
      new AnnotationConfigWebApplicationContext();
    applicationContext.register(SpringMvcConfig.class);
    return applicationContext;
  }

  @Override
  protected String[] getServletMappings() {
    return new String[]{"/*"};
  }

}

And now last but definitely not least class: AbstractAnnotationConfigDispatcherServletInitializer. Here we can see further step in simplifying Spring initialization - we don't need to manually create contexts but just set appropriate config classes in getRootConfigClasses() and getServletConfigClasses() methods. I hope you are already familiar with those names, because they works exactly like in the former case. Of course due to this class extends AbstractDispatcherServletInitializer we can still override getServletFilters(). Finally we can implement our configuration in the following way:
public class SpringWebMvcSimpleInitializer
  extends AbstractAnnotationConfigDispatcherServletInitializer {

  @Override
  protected Class<?>[] getRootConfigClasses() {
    return new Class[] {SpringRootConfig.class};
  }

  @Override
  protected Class<?>[] getServletConfigClasses() {
    return new Class[] {SpringMvcConfig.class};
  }

  @Override
  protected String[] getServletMappings() {
    return new String[]{"/*"};
  }

}

If you like to see wider context please follow examples in my GitHub repo: https://github.com/jkubrynski/spring-java-config-samples/

Comments

Unknown said…
very informative. very useful. thank you for sharing.
checkoutDigital Marketing Company In Pune
Unknown said…
The above information shared is very knowledgeable and useful. Thank you for sharing.
checkoutDigital Marketing Agency In Pune
Swapnil Taware said…
Very Nice Article. Its very Informative.
Check Out : Digital Marketing Company In Pimpri Chinchwad
Vaibhav Sinha said…
Awesome article! You are providing us very useful information. Thank you for sharing. Check out Digital Marketing Institute in Pune
oshin. said…

Very interesting article! Thanks for sharing this information. If you are interested in learning digital marketing, here is a complete list of the best online digital marketing courses with certifications. In this article, you will learn about digital marketing and its different strategies, the need for doing digital marketing, the scope of digital marketing, career opportunities after doing online digital marketing, and many more.
Visit-
Online Digital Marketing Courses

vijay kumar said…
This is wonderful blog. Very interesting. This blog is helpful for me. keep on writing your content is really helpful and I will wait for the next blog form your side.
Financial Modeling Courses in India
s said…
Thank you for sharing this helpful information. Much more information is also available on Digital Marketing Courses in Pune with Placement
Disha said…
What an amazing article. You can also read https://iimskills.com/top-10-digital-marketing-courses-in-egypt/ and you will learn more about Digital Marketing.
Rohit said…
I found the content really interesting and innovative. Loved this unique idea of presenting the article. Also, if anyone is looking for Digital marketing courses in Agra, then this article is for you: Digital marketing courses in Agra
oshin99 said…
Thanks for sharing details on spring web initialization. If you are interested in learning digital marketing, here is a list of the top 13 digital marketing courses in Ahmedabad with placements. This article will help you decide which institute is best for you to learn digital marketing and will help you to become an efficient and productive digital marketer.
Visit- Digital Marketing Courses in Ahmedabad
Subhasis said…
Nice article. Very helpful information. Interested about digital marketing in Dehradun! Visit us to know more: //iimskills.com/top-15-digital-marketing-courses-in-dehradun
DMCITRN1 said…
Very interesting article about web applications using JAWA in a very comprehensive manner with code sample and transcript. Thanks for sharing. If anyone wants to learn Digital Marketing, Please join the highly demanded and most sought skill by the professionals in all streams due to the remarkable growth predicted by international survey agencies. So join today. Find out more detail at
Digital marketing courses in france
pooja said…
This article has an excellent information on the Top 10 Digital marketing Course. Refer to know more.
Digital marketing courses in New zealand
Oldest Older 201 – 228 of 228

Popular posts from this blog

Using jstat to report custom JVM metric sets

Including Java agent in standalone Spring Boot application