How do I manually autowire a bean with Spring?

Aaron Digulla picture Aaron Digulla · Aug 15, 2012 · Viewed 27.4k times · Source

I have a bean B which I have to create myself (using new B()) and which has @Autowire and @PostConstruct annotations.

How do I make Spring process these annotations from my bean A?

Related question:

Answer

AlexR picture AlexR · Aug 15, 2012

Aaron, I believe that your code is correct but I used the following:

B bean = new B();
AutowireCapableBeanFactory factory = applicationContext.getAutowireCapableBeanFactory();
factory.autowireBean( bean );
factory.initializeBean( bean, "bean" );

The first method will process @Autowire fields and methods (but not classic properties). The second method will invoke post processing (@PostConstruct and any defined BeanPostProcessors).

Application context can be obtained in a bean if it implements ApplicationContextAware interface.