How do I manually autowire a bean with Spring?

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.


Another option is to let the spring container create automatically a new bean (instead of creating a new instance yourself with the new keyword). Inside a class that needs to instantiate a new been programmatically, inject an instance of AutowireCapableBeanFactory :

@Autowired
private AutowireCapableBeanFactory beanFactory;

Then:

B yourBean = beanFactory.createBean(B.class);

The container will inject instances annotated with @Autowired annotations as usual.