我会添加一个像这样可以访问应用程序Context的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");
}
}