上下文層次結構

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.