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

huangapple go评论189阅读模式
英文:

Inject list of beans implementing same interface

问题

假设我有以下接口
```java
public interface Handler {
    void handle(Object o);
}

和实现

public class PrintHandler implements Handler {
    void handle(Object o) {
        System.out.println(o);
    }
}
public class YetAnotherHandler implements Handler {
    void handle(Object o) {
        // 做一些操作
    }
}

我想将所有Handler子类注入到某个类中

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

我如何使用Quarkus实现这一点?


<details>
<summary>英文:</summary>

Supposing I have following interface
```java
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&lt;Handler&gt; handlers;
}

How can I achieve this using Quarkus?

答案1

得分: 14

所有的实现都需要标记为@ApplicationScoped,如下所示:

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

在想要注入所有实现的类中,使用:

@Inject
Instance<Handler> handlers;

这个Instance是从javax.enterprise.inject.Instance;中导入的。

这个handlers变量将拥有Handler接口的所有实现。

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;
}
英文:

All the implementation needs to be marked for @ApplicationScoped like:

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

In the class where you want to inject all the implementations, use

@Inject
Instance&lt;Handler&gt; 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&lt;Handler&gt; handlers;

@GET
@Produces(MediaType.TEXT_PLAIN)
public List&lt;String&gt; handle() {
    List&lt;String&gt; list = new ArrayList&lt;&gt;();
    handlers.forEach(handler -&gt; list.add(handler.handle()));
    return list;
}

huangapple
  • 本文由 发表于 2020年7月25日 03:22:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/63080232.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定