此版本仍在开发中,尚不被认为是稳定的。对于最新的稳定版本,请使用 Spring Framework 6.2.10! |
上下文层次结构
DispatcherServlet
期望WebApplicationContext
(平原的延伸ApplicationContext
) 用于自己的配置。WebApplicationContext
有一个指向ServletContext
和Servlet
与之关联。它还绑定到ServletContext
这样应用程序就可以在RequestContextUtils
查找WebApplicationContext
如果他们需要访问它。
对于许多应用程序,具有单个WebApplicationContext
很简单,就足够了。也可以有一个上下文层次结构,其中一个根WebApplicationContext
在多个DispatcherServlet
(或其他Servlet
) 实例,每个实例都有它自己的子WebApplicationContext
配置。 看的附加功能ApplicationContext
有关上下文层次结构功能的更多信息。
根WebApplicationContext
通常包含基础设施 bean,例如数据存储库和需要在多个之间共享的业务服务Servlet
实例。 这些 bean是有效继承的,并且可以在特定于 Servlet 的 孩子WebApplicationContext
,它通常包含给定Servlet
. 下图显示了这种关系:

以下示例配置WebApplicationContext
等级制度:
-
Java
-
Kotlin
public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { RootConfig.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { App1Config.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/app1/*" };
}
}
class MyWebAppInitializer : AbstractAnnotationConfigDispatcherServletInitializer() {
override fun getRootConfigClasses(): Array<Class<*>> {
return arrayOf(RootConfig::class.java)
}
override fun getServletConfigClasses(): Array<Class<*>> {
return arrayOf(App1Config::class.java)
}
override fun getServletMappings(): Array<String> {
return arrayOf("/app1/*")
}
}
如果不需要应用程序上下文层次结构,则应用程序可以通过getRootConfigClasses() 和null 从getServletConfigClasses() . |
以下示例显示了web.xml
等效:
<web-app>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/root-context.xml</param-value>
</context-param>
<servlet>
<servlet-name>app1</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/app1-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>app1</servlet-name>
<url-pattern>/app1/*</url-pattern>
</servlet-mapping>
</web-app>
如果不需要应用程序上下文层次结构,应用程序可以仅配置“root”上下文,并保留contextConfigLocation Servlet 参数为空。 |