Guice injectMembers method
I understand the benefits of using constructor inj开发者_StackOverflow社区ection over setter injection but in some cases I have to stick with setter-based injection only.
My question is how to inject members of all the setter-based injection classes using injector.injectMembers()
method?
//I am calling this method in init method of my application
private static final Injector injector = Guice.createInjector(new A(), new B());
//Injecting dependencies using setters of all classes bound in modules A and B
injector.injectAllMembers()??
Why do you need to inject dependencies manually?
Guice injects dependencies into the fields and methods automatically. Use:
YourClass yourClass = injector.getInstance(YourClass.class);
Guice documentation:
Whenever Guice creates an instance, it performs this injection automatically (after first performing constructor injection), so if you're able to let Guice create all your objects for you, you'll never need to use this method.
You need to inject members by yourself only into a manually created instance like this:
YourClass yourClass = new YourClass();
injector.injectMembers(yourClass);
Or you can use something like that:
public class YourClassProvider implements Provider<YourClass> {
private final Injector injector;
@Inject
public YourClassProvider(Injector injector) {
this.injector = injector;
}
public YourClass get() {
YourClass yourClass = new YourClass();
injector.injectMembers(yourClass);
return yourClass;
}
}
In any case, setters of YourClass should be annotated with @Inject.
精彩评论