【问题标题】:Spring Boot - Get all methods with custom annotationSpring Boot - 使用自定义注释获取所有方法
【发布时间】:2018-08-29 12:04:59
【问题描述】:

我有一个自定义注释:

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

这样使用:

@Service
class MyService {

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

在另一个服务中,每次发生某些事情时,我都想调用每个带有@Listener 注释和Thing 类型参数的函数。 如果不遍历上下文中的所有 bean 并检查所有方法,我该如何做到这一点?

【问题讨论】:

  • 当Thing的方法被调用,然后通知@Listener注解的方法?你是说?
  • 我有另一个服务从外部服务接收一些不同类型的数据。每次我得到一个新数据时,我都会解析它,然后我想用 @Listener 注释和我刚刚收到的类型的参数调用所有函数
  • 使用spring AOP会更容易控制

标签: spring spring-boot reflection annotations kotlin


【解决方案1】:

您可以使用以下内容:

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

【讨论】:

    【解决方案2】:

    你可以使用java的org.reflections:

    Set&lt;Method&gt; allMethods = new Reflections().getMethodsAnnotatedWith(yourAnnotation.class);

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-07
      • 2021-11-21
      • 2021-12-25
      • 2023-01-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多