具有Web应用程序上下文的Spring上下文层次结构

aha*_*aha 10 java spring spring-mvc

我正在处理一个Spring MVC Web应用程序,该应用程序是使用一个引导程序DispatcherServlet.它创建了一个XmlWebApplicationContext管理整个应用程序:

<servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:springmvc-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
Run Code Online (Sandbox Code Playgroud)

现在有一些模块应该在运行时使用a加载ContextSingletonBeanFactoryLocator.因此每个模块都有自己的模块ClasspathXmlApplicationContext.因此,一个模块可以从中引用bean XmlWebApplicationContext,它应该附加到XmlWebApplicationContext形成一个Context Hierarchy,其中XmlWebApplicationContext应该扮演父级角色和ClasspathXmlApplicationContext模块子角色的角色.不幸的是我无法使用它们连接它们

<beans>
    <bean id="moduleContext"
        class="org.springframework.context.support.ClassPathXmlApplicationContext">
        <constructor-arg>
            ...
        </constructor-arg>
        <constructor-arg ref="parentContext" />
    </bean>
</beans>
Run Code Online (Sandbox Code Playgroud)

因为到目前为止我找不到WebApplicationContext这个名字parentContext.我是否忽略了某些东西,或者是否有更好/更简单的方式以不同的方式实现同​​样的目标?

Vin*_*ers 2

如果您使用注释,您可以这样做:

@Inject
private XmlWebApplicationContext context;

@Inject
private List<ClassPathXmlApplicationContext> childs;

@PostConstruct
public void refreshContext() {
    for(ClassPathXmlApplicationContext appContext : childs) {
        appContext.setParent(context);
    }
    context.refresh();
}
Run Code Online (Sandbox Code Playgroud)

您也可以通过使用接口 InitializingBean 和 ApplicationContextAware 在没有注释的情况下完成此操作。

编辑: childs按类型自动装配,因此 Spring 将注入作为 ClassPathXmlApplicationContext 实例的所有 bean。