Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guice injectMembers method

Tags:

guice

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()??
like image 575
Abidi Avatar asked Feb 25 '11 10:02

Abidi


People also ask

What does @inject do in Guice?

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.

What is @inject annotation in Guice?

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.

What is @named annotation in Guice?

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

Can Guice inject null?

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 .


1 Answers

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.

like image 142
Pavel Avatar answered Oct 08 '22 13:10

Pavel