Anand
Anand

Reputation: 21338

How Spring Ioc container interacts with Tomcat container

I am familiar with the Spring Framework and have done some work in it.

In one of my interviews, I was asked "there is a web application deployed in Apache Tomcat; tell me how does the "Tomcat container" (used for servlets) interact with "Spring IoC container" (used for Spring beans)?"

I couldn't understand what the interviewer meant by that and was left speechless. Can someone please clarify what this question was about and what a reasonable answer to it might be?

Upvotes: 11

Views: 4171

Answers (3)

Angad
Angad

Reputation: 3429

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.

Upvotes: 3

emeraldjava
emeraldjava

Reputation: 11212

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.

Upvotes: 7

wbdarby
wbdarby

Reputation: 1159

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>

Upvotes: 3

Related Questions