Подтвердить что ты не робот

Как программно создавать определение bean с помощью вложенных свойств?

Я хочу программно добавить определение bean в контекст приложения, но некоторые свойства этого определения являются другими beans из этого контекста (я знаю их имена). Как я могу сделать это, чтобы эти свойства были введены?

Например:

GenericBeanDefinition beanDef = new GenericBeanDefinition();
beanDef.setBeanClass(beanClass);

MutablePropertyValues values = new MutablePropertyValues();
values.addPropertyValue("intProperty", 10);
values.addPropertyValue("stringProperty", "Hello, world");
values.addPropertyValue("beanProperty", /* What should be here? */);

beanDef.setPropertyValues(values);

Я использую Spring 3.0.

4b9b3361

Ответ 1

Используйте RuntimeBeanReference:

values.addPropertyValue("beanProperty", new RuntimeBeanReference("beanName")); 

Ответ 2

Я бы добавил bean, как это, который имеет доступ к applicationContext:

public class AppContextExtendingBean implements ApplicationContextAware{


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException{

        AutowireCapableBeanFactory beanFactory = applicationContext.getAutowireCapableBeanFactory();

        // do it like this
        version1(beanFactory);

        // or like this
        version2(beanFactory);

    }

    // let spring create a new bean and then manipulate it (works only for singleton beans, obviously) 
    private void version1(AutowireCapableBeanFactory beanFactory){
        MyObject newBean = (MyObject) beanFactory.createBean(MyObject.class,AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
        newBean.setBar("baz");
        newBean.setFoo("foo");
        newBean.setPhleem("phleem");
        beanFactory.initializeBean(newBean, "bean1");
    }

    // create the object manually and then inject it into the spring context
    private void version2(AutowireCapableBeanFactory beanFactory){
        MyObject myObject=new MyObject("foo","phleem");
        myObject.setBar("baz");
        beanFactory.autowireBean(myObject);
        beanFactory.initializeBean(myObject, "bean2");
    }


}

Ответ 3

Я нашел решение. Я должен использовать другой BeanDefinition как свойство, например:

GenericBeanDefinition bd2 = new GenericBeanDefinition();
bd2.setBeanClass(Dependency.class);

GenericBeanDefinition bd1 = new GenericBeanDefinition();
bd1.setBeanClass(Component.class);

MutablePropertyValues values = new MutablePropertyValues();
values.addPropertyValue("dependency", bd2);

bd1.setPropertyValues(values);

Ответ 4

Вы можете: