两个DispatcherServlet共享相同的ApplicationContext

时间:2014-12-17 11:41:36

标签: spring spring-mvc servlets

我有两个DispatcherServlets。一个在web.xml中配置,另一个在我的org.springframework.web.WebApplicationInitializer实现中配置。据我所知,我创建了两个ApplicationContexts。问题是他们必须共享相同的ApplicationContext。 如果有助于理解我的问题,初始化看起来像这样。 web.xml中:

<servlet>
        <servlet-name>web-xml-dispatcher</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>WEB-INF/dispatcher-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>web-xml-dispatcher</servlet-name>
        <url-pattern>/web-test/*</url-pattern>
    </servlet-mapping>

WebApplicationInitializer:

public class WebAppInit implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.scan("com.test");
        DispatcherServlet servlet = new DispatcherServlet(context);
        ServletRegistration.Dynamic dynamic = servletContext.addServlet("initializer-dispatcher", servlet);
        dynamic.addMapping("/init-test/*");
    }
}

那么,有没有办法在像这样配置的调度程序之间共享一个ApplicationContext?

1 个答案:

答案 0 :(得分:0)

您必须定义根Web应用程序上下文:

<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>

<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

默认情况下,Spring会将servlet上下文连接到根上下文。