Spring @Autowired on a class new instance

Spring itself offers some functionality for doing auto-wiring in your objects
which you created by new or newInstance() or whatever.

To use it you need an AutowireCapableBeanFactory
which you get by Spring’s normal dependency injection with @Autowired.

@Autowired
private  AutowireCapableBeanFactory autowireCapableBeanFactory;

Then you use its autowireBean(Object) method
to inject the @Autowired properties into your bean.

Object myBean = map.get(className).newInstance();
autowireCapableBeanFactory.autowireBean(myBean);

Design note:

Think well if you really need the approach above.
The javadoc of AutowireCapableBeanFactory advises against using this interface for most use-cases:

This subinterface of BeanFactory is not meant to be used in normal application code: stick to BeanFactory or ListableBeanFactory for typical use cases.

Integration code for other frameworks can leverage this interface to wire and populate existing bean instances that Spring does not control the lifecycle of. This is particularly useful for WebWork Actions and Tapestry Page objects, for example.

Leave a Comment