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 {

  protected WebApplicationContext createRootApplicationContext() {
    AnnotationConfigWebApplicationContext applicationContext =
      new AnnotationConfigWebApplicationContext();
    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 {

  protected WebApplicationContext createRootApplicationContext() {
    AnnotationConfigWebApplicationContext applicationContext =
      new AnnotationConfigWebApplicationContext();
    return applicationContext;

  protected WebApplicationContext createServletApplicationContext() {
    AnnotationConfigWebApplicationContext applicationContext =
      new AnnotationConfigWebApplicationContext();
    return applicationContext;

  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 {

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

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

  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/


nanosik said…
Great job Kuba, as always :)
Unknown said…
Spring Boot is also a great addition to the Spring family especially for smaller projects and on the beginning of the development.
Unknown said…
You're right, but problem with Spring Boot are big lacks in documentation. Unfortunatelly recently we had to abamdon it due to interation testing problems. But iI think that Comditional introduced in Spring 4 is really powerful and it will move development simplification to the next level :)
del65 said…
Spring Roo is also a great way to start and configure a simple Spring project from scratch (and update it afterwards).
Unknown said…
The problem with Spring Roo is that it generates code that your have to maintain later. Spring Boot is operating on "convention over configuration" and that's its power :)
sanjeev sinha said…

I tried the same.

In my case the getRootConfigClasses does not return the ApplicationConfig class where I do the JPA config.What could be the potential reason behind that.
This how the logs is:
6:38:35,992 INFO [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/odb]] (ServerService Thread Pool -- 139) Spring WebApplicationInitializers detected on classpath: [com.amadeus.odb.config.RestWebApplicationInitializer2@366a0fd0]
16:38:36,107 INFO [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/odb]] (ServerService Thread Pool -- 139) Initializing Spring FrameworkServlet 'dispatcher',

Then I was expecting Persistence unit log to appear, which is not happening.
An hint would be of great help.
Unknown said…
Sanjeev - could you provide more details? Maybe you're able to share some code on Github?
Unknown said…
Any suggestion about how the java configuration will change in case we want to use Spring Data with MongoDB for web application...I surf the web ( i found ton of example using web.xml or *-servlet.xml) but did not find any good example which give good information about java configuration for Spring Data, MongoDB and ThymeLeaf based web application....
Unknown said…
@Mayur in your case you just have to create @Configuration extending AbstractMongoConfiguration and annotate it by @EnableMongoRepositories. Please check this article: http://java.dzone.com/articles/how-use-spring-data-mongodb
Edward Beckett said…
"You're right, but problem with Spring Boot are big lacks in documentation."

This is one of the biggest problems I've had trying to migrate to Spring Boot. I look at projects developed on Spring Boot, such as jhipster and immediately think, "How did they know how to implement this functionality?"

Without knowing 'Spring' Spring boot won't get you very far at all..
Unknown said…
Edward - now it's much better with Spring Boot documentation - there is even stable version of Spring Boot. I was writing it one year ago :)
Unknown said…
I had to change

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


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

to make form logins work. So without the "*"
AurĂ©liusz said…
That's exactly what I did, but I ran into that
No mapping found for HTTP request with URI [/helloworld.jsp] in DispatcherServlet with name 'dispatcherServlet'
Unknown said…
Actually I am trying to initialize ApplicationContext and SecurityConfig using java config. But I am getting error like 'Cannot initialize context because there is already a root application context present - " + "check whether you have multiple ContextLoader'. How to resolve this issue in spring using java configuration.

Any help is appreciated.
Krzysztof said…

simply and clever. I like it.
Ram Niwas said…
This comment has been removed by the author.
rana said…
This is a very amazing post for cheap web hosting services. in this post, you have provided all the basic information regarding.
website builder for reseller
rana said…
Comfortabl y, the post is really the freshest on that deserving topic. I harmonise with your conclusions and definitely will thirstily look forward to your next updates.

private label website builder
rana said…
Thank you for the link building list.I am going jot down this because it will help me a lot.Great blog! Please keep on posting such blog.

white label website builder
JJ-Spring said…
How do you do the same in spring boot?
Laura Bush said…
I really like and appreciate your work which is about java course. The article you have shared here is great. I read your post with carefully, the points you mentioned can be very helpful. It is nice seeing your wonderful post. Best Advanced Java Course in Delhi
Mani Mekalai said…
This comment has been removed by the author.
raj khan said…
Soma pill is very effective as a painkiller that helps us to get effective relief from pain. This cannot cure pain. Yet when it is taken with proper rest, it can offer you effective relief from pain.
This painkiller can offer you relief from any kind of pain. But Soma 350 mg is best in treating acute pain. Acute pain is a type of short-term pain which is sharp in nature. Buy Soma 350 mg online to get relief from your acute pain.


Buy Soma 350 mg
Soma Pill
Buy Soma 350 mg online

Buy Soma 350 mg online
Soma Pill
Buy Soma 350 mg
james john said…
The article was up to the point and described the information very effectively. Thanks to blog author for wonderful and informative post.
website development Pakistan
Adhuntt said…
Great blog thanks for sharing Masters of building brands, Adhuntt Media is making waves in the Chennai digital market! Known for their out of their box ideas, if a creative overhaul for your brand is what you need, you’ve come to the right place. Right from Search Engine Optimization-SEO to Social Media Marketing, Adhuntt Media is your pitstop for original brand identity creation from scratch.
digital marketing agency in chennai

Karuna said…
Nice blog thanks for sharing Join the Karuna Nursery Garden family and be a part of our network of home gardeners. We can help you setup the perfect front yard for your family to relax in. Reach us out to get more information on our terrace garden consultants in Chennai too.
plant nursery in chennai
Pixies said…
Excellent blog thanks for sharing Looking for the best place in Chennai to get your cosmetics at wholesale? The Pixies Beauty Shop is the premium wholesale cosmetics shop in Chennai that has all the international brands your salon deserves.
beauty Shop in Chennai
Nannie Co Pam said…
Great Article. Thank you for sharing! Really an awesome post for every one.

IEEE Final Year projects Project Centers in Chennai are consistently sought after. Final Year Students Projects take a shot at them to improve their aptitudes, while specialists like the enjoyment in interfering with innovation. For experts, it's an alternate ball game through and through. Smaller than expected IEEE Final Year project centers ground for all fragments of CSE & IT engineers hoping to assemble. Final Year Project Domains for IT It gives you tips and rules that is progressively critical to consider while choosing any final year project point.

Spring Framework has already made serious inroads as an integrated technology stack for building user-facing applications. Spring Framework Corporate TRaining the authors explore the idea of using Java in Big Data platforms.
Specifically, Spring Framework provides various tasks are geared around preparing data for further analysis and visualization. Spring Training in Chennai
Tuhin said…
keep up the good work. this is an Assam post. this to helpful, i have reading here all post. i am impressed. thank you. this is our digital marketing training center. This is an online certificate course
digital marketing training in bangalore | https://www.excelr.com/digital-marketing-training-in-bangalore
Jack sparrow said…

This post is really nice and informative. The explanation given is really comprehensive and informative. I also want to say about the seo course online
Indpac said…
Very useful blog thanks for sharing IndPac India the German technology Packaging and sealing machines in India is the leading manufacturer and exporter of Packing Machines in India.

Unknown said…
Thanks for the interesting blog that you have implemented here. Very helpful and innovative. Waiting for your next upcoming article.
Java training in chennai
Java training institute in chennai
Java course in chennai
Java training classes
Java training
Java programming classes
core java coure

w3webschool said…
Great Article. Thank you for sharing! Really an awesome post for every one.
Digital Marketing Course In Kolkata
Web Design Course In Kolkata
dataexpert said…
Great post i must say and thanks for the information. Education is definitely a sticky subject. However, is still among the leading ExcelR Digital Marketing Class In Pune topics of our time. I appreciate your post and look forward to more.
CloudLearn ERP said…
You must have a lot of pride in writing quality content. I'm impressed with the amount of solid information you have written in your article. I hope to read more.
Best Data Science training in Mumbai

Data Science training in Mumbai
ek said…
This is an awesome motivating article. I am practically satisfied with your great work. You put truly extremely supportive data. Keep it up. Continue blogging. Hoping to be perusing your next post
Courses in Digital Marketing in Pune
Indhu said…
Thanks for sharing this wonderful informations.
android training institutes in coimbatore

amazon web services training in coimbatore

big data training in coimbatore

C and C++ training in coimbatore

Blue prism training in coimbatore

artificial intelligence training in coimbatore

RPA Course in coimbatore
interiorworld said…
You are so interesting! I don't believe I've truly read through anything like that before. So wonderful to discover another person with a few unique technology thoughts on this issue. Seriously.. many thanks for starting this up. This website is something that is required on the internet, someone with a bit of originality!
Anonymous said…
Nice article, keep sharing
Anebellyliza said…
Nice Blog ! It was really a nice article and i was really impressed by reading this. Thanks for sharing such detailed information.
Data Science Training in Hyderabad
Janu said…

I feel very grateful that I read this. It is very helpful and very informative and I really learned a lot from it.

Dot Net Training in Chennai | Dot Net Training in anna nagar | Dot Net Training in omr | Dot Net Training in porur | Dot Net Training in tambaram | Dot Net Training in velachery

Anirban Ghosh said…
It's very nice to find out other writers share like minds on some content. This is the case with your article. I really enjoyed this.
SAP training in Kolkata
SAP training Kolkata
Best SAP training in Kolkata
SAP course in Kolkata
SAP training institute Kolkata

Popular posts from this blog

Understanding the first level JPA cache

Including Java agent in standalone Spring Boot application