views:

58

answers:

3

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)

+1  A: 

Not without some workarounds, as Spring knows nothing about this instance.

The real question is: why are you creating instances of a class that you want dependencies injected into manually, rather than letting Spring control it? Why isn't the class using MyClass getting MyClass injected into it?

matt b
+7  A: 

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.
}
skaffman
Good answer (+1). There's also a second method where you can influence how the autowiring happens: http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/beans/factory/config/AutowireCapableBeanFactory.html#autowireBeanProperties%28java.lang.Object,%20int,%20boolean%29
seanizer
A: 

You can also mark your MyClass with @Configurable annotation:

@Configurable
public 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.

glaz666