How Spring Ioc container interacts with Tomcat container

。_饼干妹妹 提交于 2020-02-17 13:46:50

问题


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?


回答1:


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.




回答2:


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>



回答3:


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.



来源:https://stackoverflow.com/questions/27509861/how-spring-ioc-container-interacts-with-tomcat-container

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!