如何以编程方式创建具有注入属性的bean定义?

Fix*_*int 20 java spring dependency-injection dynamic

我想以编程方式将bean定义添加到应用程序上下文中,但该定义的某些属性是来自该上下文的其他bean(我知道它们的名称).我该怎么做才能注入这些属性?

例如:

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);
Run Code Online (Sandbox Code Playgroud)

我正在使用Spring 3.0.

axt*_*avt 21

用途RuntimeBeanReference:

values.addPropertyValue("beanProperty", new RuntimeBeanReference("beanName")); 
Run Code Online (Sandbox Code Playgroud)

  • @Shooshpanchick:`BeanDefinition`在`RuntimeBeanReference`创建对现有类的引用时创建指定类的新内部bean. (6认同)

Sea*_*oyd 14

我会添加一个可以访问applicationContext的bean:

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");
    }


}
Run Code Online (Sandbox Code Playgroud)