java - 如何在构建期间或 Spring Boot 启动期间验证注释?
问题描述
例如,假设我有一个@TimedMillis
和一个@TimedSeconds
注释。他们所做的是记录方法执行持续时间,一个以毫秒为单位,另一个以秒为单位。
让它们都使用相同的方法是没有任何意义的。一个方法可以有这些注释之一,或者他可以没有它们,但不能同时具有它们。
我如何检查一个方法在构建过程中是否同时拥有它们(最好)?如果在构建期间不可能,我该如何在启动期间执行此操作并阻止应用程序启动?我已经看到hibernate在启动期间这样做了。虽然它没有阻止应用程序启动,但它确实阻止了应用程序工作。
解决方案
您可以使用反射库轻松扫描包及其所有子包,以查找包含使用特定注释注释的方法的类。
然后,您可以在任何您认为合适的地方注入验证逻辑。
例如,您可以:
- 添加反射依赖项:
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>0.9.12</version>
</dependency>
- 添加验证逻辑,如果需要,甚至早于 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);
});
}
推荐阅读
- cmake - check_symbol_exists 是否适用于网络驱动器?还是有其他类似的限制?
- php - 从多数组中过滤多个值
- quarkus - 在没有 docker 的情况下创建 quarkus runner
- java - Recycleview 未显示匹配父级
- android - 无法解决“在模块中发现重复的类 com.google.android.gms.internal.vision.zzdt”错误,
- python-3.x - 如何在 python 中获取合并表列重采样?
- python - 使用python中的分割从图像中提取特定区域
- jquery - JQuery - 将数组元素设置为每个属性值
- amazon-web-services - 快照大小如何影响 Amazon Redshift 中的还原过程?
- python - 我正在尝试从网站中提取特定表格,但我在执行此操作时遇到问题