英文:
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<Handler> 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 "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;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论