我如何在 Spring 中获取实现特定通用接口(interface)(例如 Filter <TestEvent
>)的所有 bean 的引用?
这是我想用最少的行数实现的:
public interface Filter<T extends Event> {
boolean approve(T event);
}
public class TestEventFilter implements Filter<TestEvent> {
public boolean approve(TestEvent event){
return false;
}
}
public class EventHandler{
private ApplicationContext context;
public void Eventhandler(DomainEvent event) {
// I want to do something like following, but this is not valid code
Map<String, Filter> filters = context.getBeansOfType(Filter<event.getClass()>.class);
for(Filter filter: filters.values()){
if (!filter.approve(event)) {
return; // abort if a filter does not approve the event
}
}
//...
}
}
我当前的实现使用反射来确定 filter.approve 是否在调用之前接受事件。 例如
Map<String, Filter> filters = context.getBeansOfType(Filter.class);
for(Filter filter: filters.values()){
if (doesFilterAcceptEventAsArgument(filter, event)) {
if (!filter.approve(event)) {
return; // abort if a filter does not approve the event
}
}
}
doesFilterAcceptEventAsArgument 完成了我希望摆脱的所有丑陋工作。有什么建议么?
最佳答案
仅供引用,我可以构建的最简单的解决方案是:
Map<String, Filter> filters = context.getBeansOfType(Filter.class);
for(Filter filter: filters.values()){
try {
if (!filter.approve(event)) {
return; // abort if a filter does not approve the event.
}
} catch (ClassCastException ignored){ }
}
它在原型(prototype)制作方面效果很好。
关于java - 获取在 Spring 中实现通用接口(interface)的所有 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3228376/