gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:43:53 25 4
gpt4 key购买 nike

我正在浏览 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com