Supposing I have following interface
public interface Handler {
void handle(Object o);
}
and implementations
public class PrintHandler implements Handler {
void handle(Object o) {
System.out.println(o);
}
}
public class YetAnotherHandler implements Handler {
void handle(Object o) {
// do some stuff
}
}
I want to inject all Handler
subclasses into some class
public class Foo {
private List<Handler> handlers;
}
How can I achieve this using Quarkus?
All the implementation needs to be marked for @ApplicationScoped like:
@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
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;
}
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