查找所有具有自定义注释的bean,并从此bean创建解析器

时间:2018-09-25 11:30:08

标签: java spring annotations

我有注释:

@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。之后,我需要这个位置:

MyHandler  handler  = resolver.getHandler(MyType.TYPE3)

如何用弹簧靴做到这一点?

1 个答案:

答案 0 :(得分:-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);
    }
}