简体   繁体   English

注入实现相同接口的bean列表

[英]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我想将所有Handler子类注入一些 class

public class Foo {
    private List<Handler> handlers;
}

How can I achieve this using Quarkus?如何使用 Quarkus 实现这一目标?

All the implementation needs to be marked for @ApplicationScoped like:所有实现都需要为@ApplicationScoped 标记,例如:

@ApplicationScoped
public class PrintHandler implements Handler {
    public String handle() {
        return "PrintHandler";
    }
}

In the class where you want to inject all the implementations, use在要注入所有实现的 class 中,使用

@Inject
Instance<Handler> handlers;

This Instance is imported from javax.enterprise.inject.Instance;Instance是从javax.enterprise.inject.Instance;

This handlers variable will have all the implementations of Handler interface.这个handlers变量将拥有Handler接口的所有实现。

javax.enterprise.inject.Instance also implements the Iterable so you can iterate to it and call the required methods. javax.enterprise.inject.Instance还实现了Iterable ,因此您可以迭代到它并调用所需的方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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