spring DispatcherServlet上下文继承

时间:2011-12-02 20:34:49

标签: java spring spring-mvc applicationcontext

通常有一个ApplicationContext(父)和0..n DispatcherServlets(孩子)。是否也可以DispatcherServlet具有另一个DispatcherServle t作为父语境,其中ApplicationContext为父级?据我所知,bean可以通过传递方式解决,因此应该可以访问应用程序上下文。

我不想将共享bean放入ApplicationContext,因为它们不得暴露给其他DispatcherServlet - 只有一个例外。

2 个答案:

答案 0 :(得分:1)

HttpServletBeanFrameworkServlet看起来您可以执行以下操作,使bar使用foo的上下文作为自己的内容:

<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>

答案 1 :(得分:1)

我扩展了DispatcherServlet。现在它完美无缺!

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;
    }
}