【问题标题】:Find all beans with custom annotation and create resolver from this beans查找所有带有自定义注释的 bean 并从此 bean 创建解析器
【发布时间】:2018-09-25 11:30:07
【问题描述】:

我有注释:

@Retention(RUNTIME)
public @interface MyHandler {
    MyType type();
}

我有 3 个班级:

@MyHandler(type = MyType.TYPE1)
@Component
public class MyFirstHandler implements MyHandler {

    public MyResponse test() {
        return new MyResponse("first");
    }

}

@MyHandler(type = MyType.TYPE2)
@Component
public class MySecondHandler implements MyHandler {

    public MyResponse test() {
        return new MyResponse("second");
    }

}

@MyHandler(type = MyType.TYPE3)
@Component
public class MyLastHandler implements MyHandler {

    public MyResponse test() {
        return new MyResponse("last");
    }

}

我需要找到所有带有@MyHandler 注释的bean 并从这个bean 创建resolver。之后我需要这个 locic:

MyHandler  handler  = resolver.getHandler(MyType.TYPE3)

用spring boot怎么办?

【问题讨论】:

  • 为什么?只需创建一个委托给ApplicationContext 的解析器,然后使用getBeansWithAnnotation 方法来检索正确的解析器。

标签: java spring annotations


【解决方案1】:

您可以创建一个自动装配 MyHandler 类型的所有 bean 的组件,然后根据查询进行过滤:

@Component
public class HandlerResolver {
    @Autowired List<MyHandler> handlers;

    public MyHandler getHander(MyType type) {
        handlers.stream()
            .filter(h -> hasAnnotation(type))
            .findFirst()
            .orElseThrow(new IllegalArgumentException("no handler found"));
    }

    private boolean hasAnnotation(MyHandler h, MyType type) {
        MyHandlerAnnotation an = h.class.getAnnotation(MyHandlerAnnotation.class);
        return an != null && an.type() == type);
    }
}

【讨论】:

    猜你喜欢
    • 2019-03-17
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 2014-11-18
    • 2012-10-07
    相关资源
    最近更新 更多