上下文层次结构
DispatcherServlet
期望WebApplicationContext
(平原的延伸ApplicationContext
) 获取其自己的配置。WebApplicationContext
具有指向ServletContext
和Servlet
与之关联的。它还绑定到ServletContext
,以便应用程序可以在RequestContextUtils
要查找WebApplicationContext
如果他们需要访问它。
对于许多应用程序,如果WebApplicationContext
简单而足够。
也可以有一个上下文层次结构,其中有一个根WebApplicationContext
在多个DispatcherServlet
(或其他Servlet
) 实例,每个实例具有
它自己的孩子WebApplicationContext
配置。
看的附加功能ApplicationContext
了解有关上下文层次结构功能的更多信息。
根WebApplicationContext
通常包含基础设施 Bean,例如数据存储库和
需要在多个Servlet
实例。那些豆子
可以有效地继承,并且可以在特定于 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 参数为空。 |