Suppose we have a package foos
containing classes, which all of them implements some IFoo
.
We also have a class, Baz
which contains a data-member, List<IFoo> fooList
.
Is it possible to inject dynamically all those IFoo
classes into fooList
?
By the way, is it a common practice? (I'm new with the DI concept)
But what is a CDI bean? A CDI bean is a POJO, plain old java object, that has been automatically instantiated by the CDI container, and is injected into all, and any qualifying injection points in the application. The CDI container initiates the bean discovery process during deployment.
In order to use the beans you create, you inject them into yet another bean that can then be used by an application, such as a JavaServer Faces application. For example, you might create a bean called Printer into which you would inject one of the Greeting beans: import javax. inject.
Injectable constructors are annotated with @Inject and accept zero or more dependencies as arguments. @Inject can apply to at most one constructor per class. @Inject is optional for public, no-argument constructors when no other constructors are present. This enables injectors to invoke default constructors.
Use the javax.enterprise.inject.Instance
interface to dynamically obtain all instances of Foo
:
import javax.annotation.PostConstruct;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;
public class Baz {
@Inject
Instance<Foo> foos;
@PostConstruct
void init() {
for (Foo foo : foos) {
// ...
}
}
}
This totally makes sense, e.g. if you want to merge the results of multiple service provider implementations. You find a good study example here.
See also:
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