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)
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)
| 归档时间: |
|
| 查看次数: |
33852 次 |
| 最近记录: |