Context Hierarchy
MockDispatcher expects a WebApplicationContext (an extension of a plain
ApplicationContext) for its own configuration. WebApplicationContext has a link to the
MockContextImpl and the MockApi with which it is associated. It is also bound to the MockContextImpl
such that applications can use static methods on RequestContextUtils to look up the
WebApplicationContext if they need access to it.
For many applications, having a single WebApplicationContext is simple and suffices.
It is also possible to have a context hierarchy where one root WebApplicationContext
is shared across multiple MockDispatcher (or other MockApi) instances, each with
its own child WebApplicationContext configuration.
See Additional Capabilities of the ApplicationContext
for more on the context hierarchy feature.
The root WebApplicationContext typically contains infrastructure beans, such as data repositories and
business services that need to be shared across multiple MockApi instances. Those beans
are effectively inherited and can be overridden (that is, re-declared) in the Servlet-specific
child WebApplicationContext, which typically contains beans local to the given MockApi.
The following image shows this relationship:
The following example configures a WebApplicationContext hierarchy:
-
Java
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/*" };
}
}
If an application context hierarchy is not required, applications can return all
configuration through getRootConfigClasses() and null from getServletConfigClasses().
|
The following example shows the web.xml equivalent:
<web-app>
<listener>
<listener-class>infra.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/root-context.xml</param-value>
</context-param>
<mockApi>
<mockApi-name>app1</mockApi-name>
<mockApi-class>infra.web.mockApi.DispatcherServlet</mockApi-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>
</mockApi>
<mockApi-mapping>
<mockApi-name>app1</mockApi-name>
<url-pattern>/app1/*</url-pattern>
</mockApi-mapping>
</web-app>
If an application context hierarchy is not required, applications may configure a
“root” context only and leave the contextConfigLocation Servlet parameter empty.
|