How do I manually autowire a bean with Spring?

Viewed 35752
2 Answers

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.

Related