Typically there is one ApplicationContext (parent) and 0..n DispatcherServlets (children). Is it also possible to have aDispatcherServlet that has another DispatcherServlet as parent context which has the ApplicationContext as parent? As I understood, beans can be resolved transitively so it should be possible to access the application context.
I don't want to put the shared beans into the ApplicationContext because they must not be exposed to other DispatcherServlet - with one exception.
From HttpServletBean and FrameworkServlet it looks like you can do the following to make bar use context of foo as its own:
<servlet>
<servlet-name>foo</servlet-name>
<servlet-class>...DispatcherServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>bar</servlet-name>
<servlet-class>...DispatcherServlet</servlet-class>
<init-param>
<param-name>contextAttribute</param-name>
<param-value>foo-servlet</param-value>
</init-param>
</servlet>
I extended the DispatcherServlet. Now it works perfectly!
public class ConfigurableDispatcherServlet extends DispatcherServlet {
private String contextParent;
/**
* Initialize and publish the WebApplicationContext for this servlet.
* <p>
* Delegates to {@link #createWebApplicationContext} for actual creation of
* the context. Can be overridden in subclasses.
*
* @return the WebApplicationContext instance
* @see #setContextClass
* @see #setContextConfigLocation
*/
protected WebApplicationContext initWebApplicationContext() {
// No fixed context defined for this servlet - create a local one.
WebApplicationContext parent = WebApplicationContextUtils.getWebApplicationContext(getServletContext(),
"org.springframework.web.servlet.FrameworkServlet.CONTEXT." + getContextParent());
WebApplicationContext wac = createWebApplicationContext(parent);
// Publish the context as a servlet context attribute.
String attrName = getServletContextAttributeName();
getServletContext().setAttribute(attrName, wac);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Published WebApplicationContext of servlet '" + getServletName() +
"' as ServletContext attribute with name [" + attrName + "]");
}
if(this.logger.isInfoEnabled()) {
this.logger.info(getServletName() + " is a child of " + parent.getDisplayName());
}
return wac;
}
public String getContextParent() {
return contextParent;
}
public void setContextParent(String contextParent) {
this.contextParent = contextParent;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With