简体   繁体   中英

Spring dynamic bean definition autowire

So first short introduction: I have a working application context, now I want to create a new bean factory that extends it with some dynamic bean definitions. So i create a new instance of DefaultListableBeanFactory passing base application context as parent. Then I create a new bean definition:

BeanDefinition beanDef = BeanDefinitionBuilder.rootBeanDefinition(beanType)
                                              .setScope(BeanDefinition.SCOPE_PROTOTYPE)
                                              .setLazyInit(false)
                                              .setAbstract(false)
                                              .setDependencyCheck(AbstractBeanDefinition.DEPENDENCY_CHECK_ALL)
                                              .getBeanDefinition();

and at the end I register it with newly created bean factory

beanFactory.registerBeanDefinition(beanName, beanDef);

then some time later i would like to get new instance of that bean so I do:

Object beanInstance = beanFactory.getBean(jobType);

now i would expect that fields annotated with @Autowired are initialized.. but no. Calling beanFactory.autowireBean(beanInstance) does not help.

After looking up some other bean definitions in base application context i can see that my definitoin does not have any attributes and that I can add them by calling beanDef.setAttribute() but that requires me to know them in advance.

Now question. Is there a way to create fully initialized bean definition programmatically so it is autowired correctly?

So so i found out what i was missing: AutowiredAnnotationBeanPostProcessor it needs to be added to bean factory to fire up the @Autowired and @Value annotations.

also for @PostConstruct and @PreDestroy you need CommonAnnotationBeanPostProcessor

Bean factory created for application context by spring boot has total of 12 bean post processors so it is possible that some other are needed to get all features.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM