在Spring环境中,查找Bean是非常方便的,但是如果是需要查询方法上的注解进行反射调用或其它,则极其不方便。

可以使用MethodIntrospector.selectMethods工具方法,通过遍历所有@Component Bean的方式,挨个查找。

示例代码如下,既能拿到Method对象,又可以拿到注解信息:

Map<String, Object> beans = applicationContext.getBeansWithAnnotation(Component.class);
beans.forEach((beanName, handler) -> {

    Map<Method, AnalysisListener> methodAnalysisListenerMap = MethodIntrospector.selectMethods(handler.getClass(),
            (MethodIntrospector.MetadataLookup<AnalysisListener>) method -> AnnotatedElementUtils.findMergedAnnotation(method, AnalysisListener.class));

});

AnalysisListener.class为自定义注解