How Spring Ioc container interacts with Tomcat container How Spring Ioc container interacts with Tomcat container spring spring

How Spring Ioc container interacts with Tomcat container


A spring web-app will define a Spring Dispatcher Servlet in its config, the apache tomcat container will initialise this servlet, the dispatcher servlet in turn initialises the application context. There is no direct interaction between the tomcat container and the Spring IOC container.


There are two primary aspects of linking Spring with Servlets. First you have to load a Spring application context, and second you need to expose those Spring-loaded objects to the Servlet. There are many ways to do this, and frameworks like CXF have built-in support for Spring.

But one of the most basic mechanisms is to use a ContextLoaderListener to load the application context and a HttpRequestHandlerServlet to initialize the servlet.

Here's a simple example:

web.xml:

<web-app>...  <context-param>    <param-name>contextConfigLocation</param-name>    <param-value>/WEB-INF/applicationContext.xml</param-value>  </context-param>  <listener>    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  </listener>  <servlet>    <servlet-name>servletBean</servlet-name>    <servlet-class>org.springframework.web.context.support.HttpRequestHandlerServlet</servlet-class>  </servlet>...</web-app>

And in /WEB-INF/applicationContext.xml:

<beans>..  <!-- Note: YourServletClass must implement HttpRequestHandler -->  <bean id="servletBean" name="servletBean" class="yournamespace.YourServletClass">    ...  </bean>...</beans>


Spring apps declare a DispatcherServlet as part of the application configuration. The DipatcherServlet is a child class of HttpServlet and hence represents the servlet for the container. The DispatcherServlet also creates a WebApplicationContext. Spring maintains an IOC container for each WebApplicationContext (there can be multiple servlets in an app). There can also be a root ApplicationContext, which is created by the ContextLoaderListener. The root ApplicationContext is a parent of all WebApplicationContext(s) in a web app. The IOC container of ApplicationContext is available to all WebApplicationContext(s).

The ServletContext remains the single mode of interaction for all web containers.