Spring Boot - 使用自定义注释获取所有方法

时间:2018-03-20 15:27:37

标签: spring spring-boot reflection annotations kotlin

我有自定义注释:

@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
@MustBeDocumented
annotation class Listener

像这样使用:

@Service
class MyService {

   @Listener
   fun onNewThing(thing: Thing) {
       ...
   }
}

在另一项服务中,每当发生某些事情时,我都希望使用@ListenerThing类型的参数调用每个注释的函数。 如果不循环遍历上下文中的所有bean并检查所有方法,我该怎么做呢?

2 个答案:

答案 0 :(得分:0)

您可以使用java的org.reflections:

Set<Method> allMethods = new Reflections().getMethodsAnnotatedWith(yourAnnotation.class);

for (Method m : allMethods) {
    if (m.isAnnotationPresent(yourAnnotation.class)) {
    //YOUR LOGIC
    }
}

答案 1 :(得分:0)

您可以使用以下内容:

Set<Method> methodsAnnotatedWith = new Reflections("com.example.spring.aop.api", new MethodAnnotationsScanner()).getMethodsAnnotatedWith(BusinessFunction.class);