加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 05:25:26 所属栏目:Java 来源:网络整理
导读:我正在处理一个使用DispatcherServlet引导的 Spring MVC Web应用程序.它创建一个管理整个应用程序的XmlWebApplicationContext: servlet servlet-namespringmvc/servlet-name servlet-classorg.springframework.web.servlet.DispatcherServlet /servlet-clas
我正在处理一个使用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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读