Always inject some fields in a Spring service through the context
I've got the following class:
@Service
public class TestService{
@Autowired
private Integer size;
private MyClass myObject;
public Test(){
开发者_如何学JAVA // Default constructor for Spring
}
public Test(MyClass myObject){
this.myObject = myObject;
}
// Getters and Setters ...
}
Now I'm instantiating my TestService
from outside this class with
new TestService(myObject);
The variable size
is of course null
. But I want it to be injected from the spring context even though I didn't inject the whole object.
Is it possible to always inject some fields?
The easiest way would be to use static AspectJ compilation (or load time weaving) and @Configurable
: any Object with the @Configurable
annotation will be autowired, even when instantiated through new()
But the more traditional way would be to wire it up programatically:
MyBean foo = new MyBean();
ApplicationContext ctx = // whereever you get your context from
ctx.getAutowireCapableBeanFactory().autowireBean(foo);
Yes, you can put an arbitrary object through the autowiring process using:
appContext.getAutowireCapableBeanFactory().autowireBean(existingBean)
You still need a reference to the appContext
to do this, though, which is up to you.
The fancier way is to use load-time weaving, using AspectJ and @Configurable
, but this takes more configuration effort - see docs.
I dont think its possible. Only the objects that spring instantiates are the ones that it manages the lifecycle of. I mean Spring has no way to know that you instantiated that object. May be if it hooked to the JVM itself it can do that but it doesnt. And philosophically its not how IoC is written and will be written.
精彩评论