2

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?

Kris Jaklik
  • 267
  • 1
  • 9
  • check this answer: [http://stackoverflow.com/a/28550486/1876620](http://stackoverflow.com/a/28550486/1876620) – fps Aug 06 '15 at 23:44
  • possible duplicate of [Spring - Programmatically generate a set of beans](http://stackoverflow.com/questions/28374000/spring-programmatically-generate-a-set-of-beans) – fps Aug 07 '15 at 00:00

1 Answers1

1

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.

Kris Jaklik
  • 267
  • 1
  • 9