首页 > 解决方案 > 如何在构建期间或 Spring Boot 启动期间验证注释?

问题描述

例如,假设我有一个@TimedMillis和一个@TimedSeconds注释。他们所做的是记录方法执行持续时间,一个以毫秒为单位,另一个以秒为单位。

让它们都使用相同的方法是没有任何意义的。一个方法可以有这些注释之一,或者他可以没有它们,但不能同时具有它们。

我如何检查一个方法在构建过程中是否同时拥有它们(最好)?如果在构建期间不可能,我该如何在启动期间执行此操作并阻止应用程序启动?我已经看到hibernate在启动期间这样做了。虽然它没有阻止应用程序启动,但它确实阻止了应用程序工作。

标签: javaspringspring-bootannotations

解决方案


您可以使用反射库轻松扫描包及其所有子包,以查找包含使用特定注释注释的方法的类。

然后,您可以在任何您认为合适的地方注入验证逻辑。

例如,您可以:

  1. 添加反射依赖项:
<dependency>
    <groupId>org.reflections</groupId>
    <artifactId>reflections</artifactId>
    <version>0.9.12</version>
</dependency>
  1. 添加验证逻辑,如果需要,甚至早于 Spring Boot 引导程序,如下所示:
  public static void main(String[] args) {
    validateAnnotations();
    SpringApplication.run(ExampleApplication.class, args);
  }

  private static void validateAnnotations() {
    Set<Method> annotatedMethods = 
      new Reflections("com.example", new MethodAnnotationsScanner())
      .getMethodsAnnotatedWith(TimedMillis.class);
    
    annotatedMethods.stream()
    .filter(method -> method.getDeclaredAnnotationsByType(TimedSeconds.class).length > 0)
    .findFirst()
    .ifPresent(method -> {
      throw new IllegalStateException("Invalid annotations for method " + method);
    });
  }


推荐阅读