AbstractAnnotationConfigDispatcherServletInitializer 中getRootConfigClasses() 和getServletConfigClasses() 的区别

DIfference between getRootConfigClasses() and getServletConfigClasses() in AbstractAnnotationConfigDispatcherServletInitializer

每个功能的用途是什么。为什么spring 给配置类 两个不同的函数?我在两者之间感到困惑,我应该使用哪一个?

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/support/AbstractAnnotationConfigDispatcherServletInitializer.html

createRootApplicationContext() The returned context ... will be established as the parent context for any DispatcherServlet application contexts. As such, it typically contains middle-tier services, data sources, etc.

createServletApplicationContext() The returned context ... typically contains controllers, view resolvers, locale resolvers, and other web-related beans.

servlet与根上下文的综合区别解释:What is the difference between ApplicationContext and WebApplicationContext in Spring MVC?

在典型的 Spring 应用程序中有 2 个 ApplicationContext 实例,一个是所谓的 root 应用程序上下文,第二个(或第三个或 . ..) 是 servlet 应用程序上下文。

root 应用程序通常包含 shared/general 资源,如 DataSource、服务、存储库等...servlet context 包含特定于此上下文的 beans,通常是视图解析器、处理程序映射、控制器等。The servlet context uses the root context as a parent 因此可以看到其中定义的 beans(root 不知道 servlet 上下文!) .

在此典型设置中,根上下文由 ContextLoaderListener and the servlet context by the DispatcherServlet 加载。

在过去,人们会写一个 web.xml,其中包含 ContextLoaderListenerservlet-listenerDispatcherServletservlet 元素。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    xsi:schemaLocation="
      http://java.sun.com/xml/ns/javaee
      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"
>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- Spring child -->
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

ContextLoaderListener 默认加载 applicationContext.xmlDispatcherServlet 加载 <servlet-name>-servlet.xml(因此加载 dispatcher-servlet.xml)。

从 Servlet 3.0 规范开始,可以将 web.xml 替换为基于 Java 的配置。 Spring 花时间提供基础 classes,它已经进行了基本配置(比如 ContextLoaderListenerDispatcherServlet 的注册)。但是,由于现在完全基于 Java 配置,因此 ContextLoaderListenerDispatcherServlet 都需要提供配置列表 classes,因为没有默认 [=62] =] 名称它可以检测加载。

所以 getRootConfigClasses() 将配置 ContextLoaderListener 并且实际上是可选的(您可以 return null 或空数组)。 getServletConfigClasses() 将配置 DispatcherServlet(并且是必需的)。