java – 使用Web应用程序上下文的Spring上下文层次结构

前端之家收集整理的这篇文章主要介绍了java – 使用Web应用程序上下文的Spring上下文层次结构前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在处理一个使用DispatcherServlet引导的 Spring MVC Web应用程序.它创建一个管理整个应用程序的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>

现在有一些模块应该使用ContextSingletonbeanfactoryLocator在运行时加载.因此每个模块都有自己的ClasspathXmlApplicationContext.所以一个模块可以引用XmlWebApplicationContext中的bean,它应该被附加到XmlWebApplicationContext以形成一个上下文层次结构,其中XmlWebApplicationContext应该扮演父类的角色,并且该模块的ClasspathXmlApplicationContext是子上下文的角色.不幸的是我无法连接他们使用

<beans>
    <bean id="moduleContext"
        class="org.springframework.context.support.ClassPathXmlApplicationContext">
        <constructor-arg>
            ...
        </constructor-arg>
        <constructor-arg ref="parentContext" />
    </bean>
</beans>

因为我没有找到没有办法给WebApplicationContext的名称为parentContext.我忽略了一些东西,还是有一种更好/更容易的方式来实现不同的方式?

解决方法

如果您使用注释,您可以这样做:
@Inject
private XmlWebApplicationContext context;

@Inject
private List<ClassPathXmlApplicationContext> childs;

@PostConstruct
public void refreshContext() {
    for(ClassPathXmlApplicationContext appContext : childs) {
        appContext.setParent(context);
    }
    context.refresh();
}

您也可以通过使用接口InitializingBean和ApplicationContextAware来进行注释.

编辑:childs是按类型自动连线的,所以Spring将注入作为ClassPathXmlApplicationContext实例的所有bean.

原文链接:https://www.f2er.com/java/122669.html

猜你在找的Java相关文章