Как установить родителя текущего beanFactory в весеннем IOC - PullRequest
0 голосов
/ 09 октября 2018

Я просматривал весеннюю документацию IOC и наткнулся на следующий фрагмент кода:

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

Согласно документации, родительский атрибут тега «ref» используется для ссылки на фабрику родительских биновтекущая фабрика бинов, но для установки родителя фабрики бинов.

Я попробовал следующий фрагмент кода.Но все равно я получаю сообщение об ошибке.

    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', определенным в пути к классуresource [applicationContext.xml]: не удается разрешить ссылку на bean-компонент tokenService в родительской фабрике: родительская фабрика недоступна в org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference (BeanDefinitionValueResolver.java:360) 1011012 * Я что-то упустил?Пожалуйста, посмотрите.

1 Ответ

0 голосов
/ 09 октября 2018

Я считаю, что проблема в том, что ваш дочерний контекст обновляется до установки родительского контекста.

Вот соответствующие конструкторы из 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);
. . .
...