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

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


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.}


You can also mark your MyClass with @Configurable annotation:

@Configurablepublic class MyClass {   @Autowired private AnotherClass instance}

Then at creation time it will automatically inject its dependencies. You also should have <context:spring-configured/> in your application context xml.


Just got the same need and in my case it was already the logic inside non Spring manageable java class which had access to ApplicationContext. Inspired by scaffman.Solved by:

AutowireCapableBeanFactory factory = applicationContext.getAutowireCapableBeanFactory();factory.autowireBean(manuallyCreatedInstance);