I understand the benefits of using constructor injection 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()??
Note that the only Guice-specific code in the above is the @Inject annotation. This annotation marks an injection point. Guice will attempt to reconcile the dependencies implied by the annotated constructor, method, or field.
Annotation Type Inject. @Target(value={METHOD,CONSTRUCTOR,FIELD}) @Retention(value=RUNTIME) @Documented public @interface Inject. Annotates members of your implementation class (constructors, methods and fields) into which the Injector should inject values.
Guice comes with a built-in binding annotation @Named that takes a string: public class RealBillingService implements BillingService { @Inject public RealBillingService(@Named("Checkout") CreditCardProcessor processor, TransactionLog transactionLog) { ... }
Guice forbids null by default So if something tries to supply null for an object, Guice will refuse to inject it and throw a NULL_INJECTED_INTO_NON_NULLABLE ProvisionException error instead. If null is permissible by your class, you can annotate the field or parameter with @Nullable .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With