Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject list of beans implementing same interface

Tags:

java

cdi

quarkus

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?

like image 305
Nikita Medvedev Avatar asked Jan 25 '23 20:01

Nikita Medvedev


1 Answers

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;
}
like image 170
Ashu Avatar answered Jan 29 '23 12:01

Ashu