java - ApplicationContext 和 ServletContext

标签 java spring spring-mvc servlets applicationcontext

当谈到 Spring MVC 应用程序时,我对两个 ApplicationContext 和 ServletContext 感到困惑。 我知道每个 Spring Web 应用程序只有一个 ApplicationContext,每个 Web 应用程序也只有一个 ServletContext。 为了初始化 ApplicationContext 和 ServletContext 的值,在 web.xml 中,我们将在 context-param 标记中添加一些内容。

这就是让我感到困惑的地方。 这两者有什么区别(我知道 ApplicationContext 有一些处理 bean 的方法)? When 我们将使用 ApplicationContextWhen 我们将使用 ServletContext

最佳答案

Servlet 上下文:

在部署 Servlet 应用程序时初始化。 Servlet Context 包含整个 servlet 应用程序的所有配置(init-param、context-params 等)。

应用上下文:

这是 Spring 特有的东西。它由 Spring 初始化。它包含在 spring 配置文件中定义的所有 bean 定义和 bean 的生命周期。 Servlet-Context 不知道这些东西。

Spring parent 和 child 中有两种类型的上下文。

Spring父上下文(应用上下文/根上下文)

  <listener>
        <listener-lass> 
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
  </listener>
  <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/service-context.xml,
            /WEB-INF/dao-context.xml,
            /WEB-INF/was-context.xml,
            /WEB-INF/jndi-context.xml,
            /WEB-INF/json-context.xml
        </param-value>
  </context-param>

role-purpose-of-contextloaderlistener-in-spring
Spring-ContextLoaderListener-And-DispatcherServlet-Concepts
spring 容器启动时会从配置文件中读取所有的 bean 定义并创建 bean 对象,并管理 bean 对象的生命周期。 此配置完全是可选的。

DispatcherServlet vs ContextLoaderListener
/declaring-spring-bean-in-parent-context-vs-child-context

Spring 子上下文(WebApplicationContext/子上下文)

<servlet>
    <servlet-name>myWebApplication</servlet-name>
    <servlet-class>
         org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>myWebApplication</servlet-name>
    <url-pattern>/app/*</url-pattern>
</servlet-mapping>

当 spring web 应用程序启动时,它会查找 spring bean 配置文件 myWebApplication-servlet.xml。它将读取所有 bean 定义并创建和管理 bean 对象的生命周期。如果父 Spring 上下文可用,它将子 Spring 上下文与父 Spring 上下文合并。如果没有可用的 Spring 父上下文,则应用程序将只有子 Spring 上下文。

关于java - ApplicationContext 和 ServletContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31931848/

相关文章:

java - 在基于java的spring配置中创建applicationContext bean

Akka 的 Java 聚合器

java - servlet spring-dispatcher 的 Servlet.init() 抛出异常(XmlBeanDefinitionStoreException)

java - 如何使用注释在 JAXB 中处理此 XML?

java - 如何拦截Spring MVC序列化响应?

Spring WebClient : What is the default multiplier for Retry. 退避?

spring - 从 IntelliJ 运行时如何激活 Spring Boot 配置文件?

java - 如何在 java spring 下拉列表中使用颜色

javascript - Javafx:如何定位场景的元素

java - Java9 的 Maven 站点插件