How to inject dependencies into a self-instantiated object in Spring?

Igor Mukhin picture Igor Mukhin · Sep 28, 2010 · Viewed 72.7k times · Source

Let's say we have a class:

public class MyClass {
    @Autowired private AnotherBean anotherBean;
}

Then we created an object of this class (or some other framework have created the instance of this class).

MyClass obj = new MyClass();

Is it possible to still inject the dependencies? Something like:

applicationContext.injectDependencies(obj);

(I think Google Guice has something like this)

Answer

skaffman picture skaffman · Sep 28, 2010

You can do this using the autowireBean() method of AutowireCapableBeanFactory. You pass it an arbitrary object, and Spring will treat it like something it created itself, and will apply the various autowiring bits and pieces.

To get hold of the AutowireCapableBeanFactory, just autowire that:

private @Autowired AutowireCapableBeanFactory beanFactory;

public void doStuff() {
   MyBean obj = new MyBean();
   beanFactory.autowireBean(obj);
   // obj will now have its dependencies autowired.
}