簡體   English   中英

如何在Spring IOC中設置當前beanFactory的父級

[英]How to set parent of current beanFactory in spring IOC

我正在閱讀春季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);
. . .

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM