Spring调度程序Servlet上下文继承

3
通常情况下,一个ApplicationContext(父级)和0..n个DispatcherServlets(子级)是存在的。同时,也可以有一个DispatcherServlet,它拥有另一个DispatcherServlet作为父上下文,而该父级上下文具有ApplicationContext作为父级。据我理解,Bean可以被传递解析,因此应该可以访问应用程序上下文。
我不想将共享的Bean放入ApplicationContext中,因为它们不能暴露给其他DispatcherServlet——唯一的例外是。

出于好奇,你为什么想要这样做? - skaffman
我有一个传统的仓库 - 服务 - 控制器架构。我想在现有的控制器层之上再加一层。 - Jan
2个回答

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

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>

看起来很棒,我会去试一下! - Jan
很遗憾,它失败了:“找不到WebApplicationContext:未注册的初始化器?” 它对你有用吗? - Jan
它报错了,显示"找不到WebApplicationContext:未注册的初始化程序?" 但是我发现我必须在contextAttribute前面加上"org.springframework.web.servlet.FrameworkServlet.CONTEXT."。现在它被正确加载了 - 但是"contextConfigLocation"没有被评估(或者由于其他原因,我的上下文XML文件没有被加载,因此没有启动任何控制器)。有什么想法吗? - Jan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接