java - 如何在spring IOC中设置当前beanFactory的父级

标签 java spring inversion-of-control

我正在浏览 Spring IOC 文档并发现以下代码片段:

<bean name="messageBroker,mBroker,MyBroker" class="com.components.MessageBroker">
    <property name="tokenBluePrint">
        <ref parent="tokenService" />
    </property>
</bean>

根据文档,“ref”标签的parent属性用于引用当前bean工厂的父bean工厂,但用于设置bean工厂的父工厂。

我尝试过以下代码片段。但我仍然收到错误。

    String[] xmlFies=new String[1];
    xmlFies[0]="applicationContext.xml";

    ClassPathXmlApplicationContext parentContext=new    ClassPathXmlApplicationContext("tokenConfiguration.xml");
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(xmlFies);
    context.setParent(parentContext);
    context.getBeanFactory().setParentBeanFactory(parentContext.getBeanFactory());
    context.close();
    parentContext.close();

错误:

原因:org.springframework.beans.factory.BeanCreationException:创建在类路径资源[applicationContext.xml]中定义的名称为“messageBroker”的bean时出错:无法解析对父工厂中bean“tokenService”的引用:否母厂可用 在 org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:360)

我错过了什么吗?请看一下。

最佳答案

我认为问题在于您的子上下文在设置父上下文之前刷新。

以下是来自 ClassPathXmlApplicationContext 的相关构造函数:

// this is the constructor that 'context' is using, and refresh is defaulted to true
public ClassPathXmlApplicationContext(String... configLocations) throws BeansException {
    this(configLocations, true, null);
}

// the constructor that both others are calling
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
        throws BeansException {
    super(parent);
    setConfigLocations(configLocations);
    if (refresh) {
        // you don't want to refresh until your parent context is set
        refresh();
    }
}

// the constructor I think you should use, it will set the parent first and then refresh
public ClassPathXmlApplicationContext(String[] configLocations, ApplicationContext parent) throws BeansException {
    this(configLocations, true, parent);
}

我会使用最后一个构造函数,以便在调用 refresh() 之前设置父上下文。

像这样:

String[] xmlFies=new String[1];
xmlFies[0]="applicationContext.xml";

ClassPathXmlApplicationContext parentContext = new ClassPathXmlApplicationContext("tokenConfiguration.xml");
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(xmlFies, parentContext);
. . .

关于java - 如何在spring IOC中设置当前beanFactory的父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52726461/

相关文章:

java - Maven-关系 : find dependent projects

java - 如何让 Spring Boot 基于外部配置配置 RabbitMQ 配置?

java - 按顺序使用 REST API,多线程环境中每次调用之间至少间隔 100 毫秒。 (带 RestTemplate)

java - Java中的上下文到底是什么?

java - 使用 JSP 作为 View 引擎注销的 Spring Boot 安全性不起作用

.net - 在 Unity 中使用泛型... InvalidCastException

java - 调用接口(interface)中的私有(private)方法

java - 如果某些 bean 仅在测试模式下存在,如何以正确的顺序初始化 bean?

java - IOC 容器是服务定位器模式的示例吗?

c# - 通用接口(interface)的运行时转换