上下文层次结构

DispatcherServlet 需要一个 WebApplicationContextApplicationContext 的一个扩展)用于其自身的配置。WebApplicationContext 链接到它所关联的 ServletContextServlet。它也绑定到 ServletContext,这样应用程序就可以使用 RequestContextUtils 上的静态方法来查找 WebApplicationContext,如果它们需要访问它的话。

对于许多应用程序来说,拥有一个单一的 WebApplicationContext 既简单又足够。也可以拥有一个上下文层次结构,其中一个根 WebApplicationContext 在多个 DispatcherServlet(或其他 Servlet)实例之间共享,每个实例都有自己的子 WebApplicationContext 配置。有关上下文层次结构功能的更多信息,请参阅 ApplicationContext 的额外功能

WebApplicationContext 通常包含基础设施 bean,例如需要在多个 Servlet 实例之间共享的数据仓库和业务服务。这些 bean 可以被子 Servlet 专用的 WebApplicationContext 有效地继承和覆盖(即重新声明),子 WebApplicationContext 通常包含与给定 Servlet 局部的 bean。下图展示了这种关系。

mvc context hierarchy

以下示例配置了 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() 返回所有配置,并通过 getServletConfigClasses() 返回 null

以下示例显示了等效的 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>
如果不需要应用程序上下文层次结构,应用程序可以只配置一个“根”上下文,并将 contextConfigLocation Servlet 参数留空。
© . This site is unofficial and not affiliated with VMware.