How to inject all implementations of an Interface?
Suppose you have multiple implementations of an Interface and you want all the implementations injected.
For example:
Handler is an Interface and it has three implementations.
public interface Handler {
String handle();
}
All the implementation needs to be marked for @ApplicationScoped like:
import javax.enterprise.context.ApplicationScoped;
@ApplicationScoped
public class PrintHandler implements Handler {
public String handle() {
return "PrintHandler";
}
}
In the class where you want to inject all the implementations, use
@Inject
Instance<Handler> handlers;
This Instance is imported from javax.enterprise.inject.Instance;
This handlers the variable will have all the implementations of Handler interface.
javax.enterprise.inject.Instance also implements the Iterable so you can iterate to it and call the required methods.
@Inject
Instance<Handler> handlers;
@GET
@Produces(MediaType.TEXT_PLAIN)
public List<String> handle() {
List<String> list = new ArrayList<>();
handlers.forEach(handler -> list.add(handler.handle()));
return list;
}
Top comments (0)