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

我想以编程方式将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); 

我正在使用Spring 3.0。

使用RuntimeBeanReference

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

我会添加一个可以访问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"); } } 

我找到了解决方案。 我必须使用另一个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); 

您可以:

  • 使用javaconfig项目。
  • 使用BeanDefinitionParser – 但写起来有点难看。