我有注释:
@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)
如何用弹簧靴做到这一点?
答案 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);
}
}