Context Hierarchy

DispatcherServlet 預期使用 WebApplicationContext (一個普通 ApplicationContext 的擴展) 來進行自身的組態。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 參數留空。