【问题标题】:How Spring Ioc container interacts with Tomcat containerSpring Ioc 容器如何与 Tomcat 容器交互
【发布时间】:2015-02-15 01:44:59
【问题描述】:

我熟悉 Spring Framework 并在其中做过一些工作。

在我的一次采访中,有人问我“Apache Tomcat 中部署了一个 Web 应用程序;告诉我“Tomcat 容器”(用于 servlet)如何与“Spring IoC 容器”交互"(用于 Spring bean)?"

我无法理解面试官的意思,无言以对。有人能澄清一下这个问题是关于什么的吗?这个问题的合理答案可能是什么?

【问题讨论】:

    标签: java spring tomcat ioc-container


    【解决方案1】:

    一个 spring web-app 将在其配置中定义一个 Spring Dispatcher Servlet,apache tomcat 容器将初始化这个 servlet,dispatcher servlet 依次初始化应用程序上下文。 tomcat容器和Spring IOC容器之间没有直接的交互。

    【讨论】:

    • 是的。 DispatcherServlet 我也认为ContextLoaderListener 也是如此。因为我们可以根据 MVC 要求选择使用DispatcherServlet
    【解决方案2】:

    将 Spring 与 Servlet 链接有两个主要方面。首先,您必须加载 Spring 应用程序上下文,其次您需要将这些 Spring 加载的对象公开给 Servlet。有很多方法可以做到这一点,像 CXF 这样的框架已经内置了对 Spring 的支持。

    但最基本的机制之一是使用ContextLoaderListener 加载应用程序上下文并使用HttpRequestHandlerServlet 初始化servlet。

    这是一个简单的例子:

    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>
    

    而在/WEB-INF/applicationContext.xml:

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

    【讨论】:

    • 谢谢..但它似乎是针对一个 servlet..如果我的应用程序中有多个 servlet 需要 Spring 加载的对象怎么办?
    • HttpRequestHandlerServlet 使用 servlet-name 来定位作为 Servlet 的 bean。因此,如果您有多个 Servlet,只需使用具有单独 servlet 名称的多个 HttpRequestHandlerServlet 实例,并将每个实例映射到 applicationContext.xml 中的不同 bean。
    • 非常感谢..我可以运行了 :)
    【解决方案3】:

    Spring 应用程序将 DispatcherServlet 声明为应用程序配置的一部分。 DipatcherServlet 是HttpServlet 的子类,因此代表容器的servlet。 DispatcherServlet 也会创建一个WebApplicationContext。 Spring 为每个 WebApplicationContext 维护一个 IOC 容器(一个应用程序中可以有多个 servlet)。还可以有一个根ApplicationContext,它是由ContextLoaderListener 创建的。根 ApplicationContext 是 Web 应用程序中所有 WebApplicationContext(s) 的父级。 ApplicationContext 的 IOC 容器可用于所有 WebApplicationContext。

    ServletContext 仍然是所有 Web 容器的单一交互模式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-06
      • 1970-01-01
      • 2011-08-12
      • 1970-01-01
      • 2011-07-14
      • 2015-06-25
      相关资源
      最近更新 更多