Spring MVC的DispatcherServlet需要一個WebApplicationContext對象作為它的配置,WebApplicationContext包含一個指向與其關聯的ServletContent和Servlet的連結。
同時,WebApplicationContext還綁定到了ServletContent上,在需要時,應用程式可以通過RequestContextUtils上的靜态方法查找WebApplicationContext。
對于大多數應用來說,單一的WebApplicationContext就能滿足需求,同時,Spring也支援多層次的上下文結構。在該結構中,包含一個根WebApplicationContext,用來在多個DispatcherServlet或其他Servlet之間進行共享。
在典型情況下,根WebApplicationContext包含一些基礎Bean,像是資料存儲和業務服務等需要在多個Servlet執行個體間共享的Bean。這些Bean在子WebApplicationContext中被繼承,并且可以被重寫。在子WebApplicationContext中通常包含Servlet的本地Bean。
通過Java配置類定義多層Context
public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { RootConfig.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { AppConfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/app/*" };
}
}
通過web.xml定義多層Context
<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>app</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/app-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>app</servlet-name>
<url-pattern>/app/*</url-pattern>
</servlet-mapping>
</web-app>