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?
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.
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:
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.
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).
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).
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