In a typical Spring MVC project there two "containers": One created by ContextLoaderListener and the other created by DispatchServlet.
I want to know, are these really two IoC container instance?( I see two bean config files, one is root-context.xml
the other is servlet-context.xml
)
If there are 2 containers, then what's the relationship?
Can the beans declared in one container be used in the other?
From the Spring Official Website:
Again from official Doc:
Now coming to your Question, as is stated here:
Check these links
Difference between applicationContext.xml and spring-servlet.xml in Spring Framework
http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/beans.html#beans-basics
Spring MVC have atleast 2 container -
Application Context declared by
Servlet context declared by -
And a web application can define any number of
DispatcherServlet
's. Each servlet will operate in its own namespace, loading its own application context with mappings, handlers, etc. Only the root application context as loaded byContextLoaderListener
, if any, will be shared. Thus can have any number of child containers.ApplicationContext
a registry of components (beans).ApplicationContext
defines the beans that are shared among all the servlets i.e. root context configuration for every web application.spring*-servlet.xml
defines the beans that are relatedWebApplicationContexts
hereDispatcherServlet
.WebApplicationContexts
.There aren't two separate containers created. Typically, you want spring to instantiate the object declared in the servlet-context.xml when the object is required. So, you map the servlet-context.xml configuration file to the Dispatcher Servlet i.e. you want to initialize the object when a request hits the dispatcher servlet.
Where as, if you want to initialize the object and perform action when the context is being loaded you would declare the configuration file with in the
context-param
tags of your deployment descriptor.You could test this out by writing by declaring separate beans in the servlet-context.xml and root-context.xml and then, autowiring them in a custom Context Loader Listener class. You would find only the root-context instances are initialized and servlet-context beans are null.