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

How to set parent of current beanFactory in spring IOC

我正在浏览 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:创建名称为 'messageBroker' 的 bean 在 class 路径资源 [applicationContext.xml] 中定义时出错:无法解析对 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);
. . .