A context indicates an instance of Spring bean container. If we want a DispatcherServlet to dispatch the request to beans annotated with @Controller (i.e., controllers), we should provide a context containing controller beans, in other words, we should pass the location of metadata of Spring context to DispatcherServlet so that it can generate his Spring context. Typically, Spring context DispatcherServlet has contains beans related to Web MVC, such as controllers or rest controllers (beans annotated with @Controller or @RestController).
Each DispatcherServlet has one Spring context its own. If you want some beans to be shared across your web application, it doesn't be achieved by registering beans on the DispatcherServlet context.
In that case, you can register your beans on the context included in ContextLoaderListener, which is so called bootstrap context since it is root of Spring contexts of web application. DispatcherServlet contexts are children of the bootstrap context. For a beans in parent context, it is visible to the child context, but not vice versa.
Once you register your beans into the bootstrap context in ContextLoaderListener, your DispatcherServlet can access the beans.
Registering ContextLoaderListener in web.xml:
<listener>
<listner-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<!-- By default, ContextLoaderListener uses XmlWebApplicationContext
<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.XmlWebApplicationContext</param-value>
</context-param>
-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:spring-config/context-*.xml</param-value> <!-- For instance -->
</context-param>
ContextLoaderListener uses ServletContext to get the information where the metadata was placed.
Top comments (0)