Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject an array of Objects in Guice

Tags:

java

guice

I would like to achieve something similar to the following in Guice:

public MyClass {

    private final InjectedObject[] injectedObjects;

    @Inject
    public MyClass(InjectedObject[] injectedObjects) {
        this.injectedObjects=injectedObjects;
    }
}

ie I would like to be able to create a certain number of instances of an object, and inject them into another object as an array. I could probably do this instead:

public MyClass {

    private final InjectedObject[] injectedObjects;

    @Inject
    public MyClass(InjectedObjectProvider injectedObjectProvider) {
        this.injectedObjects=injectedObjectProvider.getArrayOfInjectedObjects(5);
    }
}

...but I was wondering if there was another route that was more elegant?

like image 686
Rich Avatar asked Feb 26 '09 19:02

Rich


People also ask

What is method injection in Google Guice?

Google Guice - Method Injection. Injection is a process of injecting dependency into an object. Method injection is used to set value object as dependency to the object. See the example below.

Does Guice support @inject and @named?

Tip: While we just said to use the Guice-provided @Inject and @Named, it's worthwhile to note that Guice does provide support for javax.inject.Inject and javax.inject.Named, among other Jakarta EE annotations. 3.4. Constructor Binding We can also inject a dependency that doesn't have a default no-arg constructor using constructor binding:

What is method injection in Java?

Injection is a process of injecting dependeny into an object. Method injection is used to set value object as dependency to the object. See the example below.

What is the main method of Guice?

This main method retrieves an instance of our Communication class. It also introduces a fundamental concept of Guice: the Module (using BasicModule in this example). The Module is the basic unit of definition of bindings (or wiring, as it's known in Spring).


1 Answers

Not sure if this suits your needs, but Multibindings worked for me when I needed to inject multiple elements of the same kind (it produces a set though).

like image 126
Eelco Avatar answered Oct 28 '22 02:10

Eelco