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

s said…
Thank you for sharing this helpful information. Much more information is also available on Digital Marketing Courses in Pune with Placement
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
Vikas 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 comment has been removed by the author.
asley said…
Informative post, may helpful for learners. Thanks for sharing. Content Writing Course in Bangalore
best digital marketing institute in pune

Visit Windreams

What You Will Learn?
seoBecome a digital marketing specialist by windreams informatives.Become a digital marketing specialist by
SEO (Search Engine Optimization.)
SEMBecome a digital marketing specialist by
SEM (Search Engine Marketing.)

social media marketingBecome a digital marketing specialist by
Social Media Marketing.

emaliBecome a digital marketing specialist by
Email Marketing.

Become a digital marketing specialist by
Content Marketing.



annnliyBecome a digital marketing specialist by windreams informatives.Become a digital marketing specialist by
Analytics.



graphic designBecome a digital marketing specialist by windreams informatives.Become a digital marketing specialist by
Graphic Design
Become a digital marketing specialist by
Mobile Marketing


Our Facilities?
Offline / Online Class
Duration 3 Month Only Fri / Sat / Sun
100% Job Assistance
25+ Topics
Google Certification
Scholarship Program
Wings For Dreams is a social service organization in Pune. Supporting for scholarship to youngsters which are actual want to learn digital marketing and become a financially independent. So the scholarship amount is 20,000/- , it is very big support for youngsters.

Course Fee : 25,000/- (+18% GST)
Scholarship : 20,000/-
Final Fee : 5000/- (+18% GST)
If you refer this course to your friends then you will get 200/- cashback per student.
Anonymous said…
The content is very nice and detailed.
Digital marketing courses in Agra
Rahul Kamboj said…

Thank you for sharing such great information. It has helped me in finding out more detail about content writing. Please keep it share to us, I will wait for the next blog.
Content Writing
yskjain said…
This comment has been removed by the author.
puja H said…
HI puja here. This blog was really knowledgeable as well as the detailing is done pretty well. Could easily follow and understand. Thank You.
Search Engine Marketing
neharikagupta96 said…
Great content and nice blog thanks for sharing this with us.
Spring Roo is also a great way to start and configure a simple Spring project from scratch (and update it afterward).
It is really very helpful, keep writing more such blogs.
Do read my blog too it will really help you with content writing.
we provide the Best Content Writing Courses in India.
Best Content Writing Courses in India
Riona said…
Thanks for the good effort you put to write this content. Keep it up.
Are you looking to start learning and enhance your career? Check out first our free online demo session in Digital Marketing Courses in Delhi. The courses are ready-to-implement with constantly updated curriculum, practical-oriented lessons, assignments and case studies, industry-recognized certificate.
Visit- Digital Marketing Courses in Delhi
hey, I am Suraj and doing job in an enterprise but have little confusion about financial modeling this blog has cleared all my doubts about it. Thanks for sharing such blogs.
Financial Modeling Courses in Mumbai

yishika said…
Really appreciate the hard work you have put into creating this superb article.
Digital marketing courses in Singapore
Amazing article with detailed and quality information.
Visit- Digital Marketing Courses in Abu Dhabi
Daisy said…
Hi, thanks for sharing information about spring web initialization. Keep up the great work!
If you are interested in learning digital marketing but don’t know where to start a course, here is a list of the top 10 digital marketing training institutes in India with placements. This article will help you decide which institute is best for you to learn digital marketing and will help you become a successful digital marketer and boost your career.
Digital marketing courses in India
Puja Mittal said…
Hi, this blog is very impressive. The content is well explained and formatted to suit the understanding of the readers. Even a beginners can follow the content. Thank you.
Digital marketing courses in Ghana
Anonymous said…
The article on spring web initialization is well explained in details. I found the content knowledgeable and also I'm looking forward for more such contents. Digital Marketing courses in Bahamas
Divya said…
The blog is very informative and helpful.
Digital marketing courses in Noida
Riya said…

Hi! You have provided us with informational content. Thanks for sharing.
If you are interested in building a medical career but are struggling to clear medical entrance exams, Wisdom Academy is the right place to begin. It is one of Mumbai's best NEET coaching institutes for students preparing for medical and other competitive-level entrance examinations. It offers comprehensive learning resources, advanced study apparatus, doubt-clearing sessions, regular tests, mentoring, expert counseling, and much more.
NEET Coaching in Mumbai
Melys said…
Such an informative and valuable article. It looks like you have good knowledge about Spring Web Initialization. We can not stop learning. Keep the good work. We also provide an informational and educational blog about Freelancing. Today, many people want to start a Freelance Career and they don’t know How and Where to start. People are asking about:
What is Freelancing and How Does it work?
How to Become a Freelancer?
Is working as a Freelancer a good Career?
Is there a Training for Freelancers?
What is a Freelancer Job Salary?
Can I live with a Self-Employed Home Loan?
What are Freelancing jobs and where to find Freelance jobs?
How to get Freelance projects?
How Do companies hire Freelancers?
In our Blog, you will find a guide with Tips and Steps which will help you to take a good decision. Start reading here:
What is Freelancing
Vikas said…
Highly informative tech article described very well elaborately in a decent manner with code and related notes to understand. Great effort. Thanks very much for sharing your great experience. If anyone wants to learn Digital Marketing in Austria, Please join the newly designed world-class industry-standard curriculum professional course which are highly demanded skills required by top corporates globally and other best courses as well. For more details, please visit
Digital Marketing Courses in Austria
simmu thind said…
Spring Web Initialization is now easy for me. very informative article you have shared. thanks for share to us. keep doing this work. Professional Courses
Anonymous said…
After reading your content, now I feel that on understanding Spring web initialization seems easier for me. Also, no doubt the content is really mind-blowing. Digital Marketing Courses in Faridabad
sandeep mirok said…
Understanding Spring Web Initialization is easy by your efforts. this information is unique from others. This is really good i appreciate you work. Digital marketing courses in Kota
punithaselvaraj said…
as you said. This blog is very helpful for beginners. Keep sharing.
Financial Modeling Courses in India
DMC Germany said…
Hi, Informative blog on Understanding Spring Web Initialization. The way blog is well written and I liked the way blogger has written its impressing.
Digital marketing courses in Germany
JAke Leonel said…
This is a very useful post for me. This will absolutely be going to help me in my project.
male masturbation cup
rotating masturbation cup
DMC Vancouver said…
Great post! I really enjoyed reading it. I wanted to leave a little comment to support you and wish you a good continuation. Wishing you the best of luck for all your blogging efforts. Digital Marketing Courses in Vancouver transforms you into a complete Digital Marketer with expertise in modules like SEO, Social Media Marketing, PPC, Analytics, Content, Mobile, Email marketing. We offer courses which are ready-to-implement with newly updated syllabus, practically based lessons, interactive classroom, assignments and case studies, Master certification, affordable pricing and free demo.
Digital Marketing Courses in Vancouver
nancy yadav said…
Understanding Spring Web Initialization is here in this blog which is described by you very well. specially thanks to the writer for this blog. if you are looking for the digital marketing courses in bhutan then you will get a lot info in this link please check- Digital marketing Courses in Bhutan
anu.the.dreamer said…
this blog gave good understanding on web initializing, useful information and nice writing.
Digital marketing courses in Raipur
vcare1234567890 said…
PL-900 certification is excellent for individuals and businesses aiming to increase productivity by automating crucial operations, data analysis to uncover business insights, and creating user-friendly app experiences. Attendees of this PL-900 certification training will gain a thorough understanding of developing new solutions using the Microsoft Power Platform, aiding in process automation with the Power Automate tool, learning how to use the Power BI tool for data analysis, creating chatbots with the Power Virtual Agents tool, and more.
This entry-level Microsoft Certification (PL-900) certification exam does not require prior knowledge. Professionals can use this training as a base to pursue other related certifications within the Microsoft Power Platform, such as PL200 - Microsoft Power Platform Functional Consultant, PL100 - Microsoft Power Platform App Maker, and PL400 - Microsoft Power Platform Developer.
The Microsoft Power Platform Fundamentals certification training is a two-day training that includes pre-reading materials, practice exams, access to Microsoft and Microtek Learning resources, and a copy of the course materials. The PL-900 certification training help participants in preparation for the PL-900 certification exam. The PL 900 certification exam is available in two formats: in-person at nearby Pearson Vue test centers or online using a web-proctored mode. It costs USD 99.
Vikas said…
A great informative tech article on the web application or website setup using XML configuration file but later as a part of development JAVA is being used due to its potential. Very helpful article well defined with code and well-described narratives. Thanks very much for sharing your great experience. If anyone wants to build his carrier in Digital Marketing then you must go through our curriculum which is designed very professionally with cutting edge of the current requirement of the corporates and based on market trends. For more detail Please visit at
Digital marketing Courses In UAE
Divya said…
The information is presented in a clear, concise manner that effectively explains the topic. keep posting more.
Data Analytics Courses In Kolkata
Great post! I didn't know that Spring could initialize a web application like that. This is definitely something I'll have to look into further. Data Analytics Courses In Coimbatore
Abdul Basith. said…
This is a great post that Gives better understanding of the basics of Spring Web initialization. It's one of the great starting point for anyone who wants to learn more about this topic. Digital Marketing Courses in Australia
abdul basith said…
Awesome blog very informative! This is a great post that explains the basics of how Spring Web initialization works. It covers the different types of initialization that can be performed, as well as the order in which they are performed. Data Analytics Courses in Mumbai
Abdul basith said…
This is an amazing blog which explains some great facts and importance of Understanding Spring Web Initialization! I believe this will be a very helpful resource for anyone who is looking to gain more knowledge in Spring web Initialization. Thanks for allowing us to read this blog! Data Analytics Courses in Gurgaon
Aarika said…
Hi, excellent informative and tech blog. The efforts put in by the blogger can be seen in the quality of the content. It has been well formatted to suit the convenience of the readers which is easy to understand and follow. Thank you for this useful tech blog.
Data Analytics Courses In Kochi
Abdul basith said…
This blog provide all the important information needed related to Understanding Spring Web Initialization. This is one of the best blog i have ever read about spring web. Moreover this post will let you know all the details so well with all the included advices and examples thanks for sharing! Data Analytics Courses In Coimbatore
JAke Leonel said…
If you want to buy the latest and trendiest celebrity costumes, 404 is a website that can make your wish come true.
Abdul Basith said…
This is a wonderfully written blog on Understanding Spring Web Initialization. Thanks for sharing it with us. Moreover this blog provided one of the most detailed blog related to Understanding Spring Web Initialization. Keep up the good work! Digital Marketing Courses in Vancouver
Hema R said…
Amazing blog. Thanks for sharing your knowledge on "Spring Boot." Your article taught me how to use a web application initializer. As a newbie, I found it helpful. Your explanation of the topic is profound. Foreseeing to gain more knowledge from your upcoming articles. Keep sharing more. Digital marketing courses in Nagpur
Marketing business is changing. Trends, technology , tactics are dunamic in nature. Digital marketing isgrowing in demand.ifanyone interested in digital marketing courses visit Digital marketing courses in Varanasi
Awesome post.. keep posting more interesting post on java.  Data Analytics Courses In Bangalore 
Abdul basith said…
This article offers all the crucial details required for comprehending Spring Web Initialization. One of the best blogs I've ever read regarding spring web is this one. Additionally, this post will inform you of all the information in great detail with all the suggestions and examples provided.
Data Analytics Courses in Ghana
Oldest Older 201 – 276 of 276

Popular posts from this blog

Using jstat to report custom JVM metric sets

Including Java agent in standalone Spring Boot application