This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

Applicationcontext. XML differs from Spring-servlet.xml

  • Is there any relationship between ApplicationContext.xml and Spring-servlet.xml in the Spring framework?

  • Can the DispatcherServlet use the properties file declared in applicationContext.xml?

  • Also, why do I need *-servlet.xml? Why is applicationContext.xml not enough?

Answer a

Spring allows you to define multiple contexts in the parent-child hierarchy.

Applicationcontext.xml defines the beans of the “root WebApp Context”, the context associated with the WebApp.

Spring-servlet.xml (whatever you want to call it) defines a bean for the application context of a servlet. There may be many such files in a WebApp (a Spring servlet) (for example: Spring1.xml for Servlet Spring 1, spring2.xml for Servlet Spring 2).

Beans in spring-servlet.xml can reference beans in ApplicationContext.xml, but not vice versa.

All Spring MVC controllers must be in the spring-servlet.xml context.

In most simple cases, the applicationContext.xml context is not required. It is typically used to contain beans shared by all servlets in webApp. If you have only one servlet, there is little point unless you have a specific purpose.

Answer two

To put it simply:

  • Applicationcontext.xml defines beans that are shared between all servlets. If your application has multiple servlets, it is useful to define shared resources in applicationContext.xml.

  • Spring-servlet.xml defines beans that are only relevant to that servlet. This is the Dispatche servlet. Therefore, your Spring MVCcontrollers must be defined in this file.

  • If you only have one servlet running in your Web application, defining all beans in spring-servlet.xml is no problem.

The article translated from Stack Overflow:stackoverflow.com/questions/3…