java - 获取在 Spring 中实现通用接口(interface)的所有 bean

标签 java spring

我如何在 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/

相关文章:

java - 如何在 DTO 中隐藏 JsonProperty?

java - 可选的 Spring bean 引用

java - Spring-Boot JPA - 使用 JSON RequestBody 中的外键插入数据库会导致空对象

java - 有没有办法在Android中绘制图形和图表?

java - 我需要在 jboss 运行后保留一个值。我需要在tomcat启动之前使用

java - 为什么下面的Java代码会出现StackOverflowError?

Java Repaint 方法在旧对象之上创建新对象

java - SAML 身份验证的用户不会出现在 Spring Security 的 SessionRegistry 中

java - jSTL 循环遍历对象中的列表

java - 测试中未抛出 MaxUploadSizeExceededException