简体   繁体   中英

Inject list of beans implementing same interface

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM