如何确保 @Scheduled 注释存在于方法中
How to make sure the @Scheduled annotation is present on the method
在我们的 Spring Boot
应用程序中,我们有一个带有 @Scheduled
注释的方法:
@Scheduled(fixedRate = 1000L * 60 * 10, initialDelay = 1000L * 60 * 5)
public void doSomethingFromTimeToTime(){....}
在我们的 Maven 构建测试阶段,我们希望确保:
- 注释存在(例如,开发人员未错误删除)和
- 包含这些精确值
有没有办法在 unit/integration 测试中以某种方式测试它?或者在构建阶段以另一种方式?
我们不需要测试 Spring 的调度程序本身,只是为了确保注释存在。
我想这样你可以使用反射轻松获得它
Class<?> cls = Class.forName(name);
cls.getDeclaredAnnotations(); // get all annotation
(cls.getDeclaredMethods()[0]).getAnnotations(); //get annotation of a method
Annotation ety = cls.getAnnotation(Annotation.class); // get annotation of particular annotation class
ref How to get the value of annotation using Reflection in Java
您可以使用 Class
的 .getAnnotation(Class<A> annotationType)
方法测试 Class
对象上是否存在注释,其中 A
是泛型类型参数,就像 T
通常是。
用法示例:
Scheduled scheduledAnnotation = MySpringScheduler.class.getAnnotation(Scheduled.class).
获得注解后,您可以使用注解提供的方法访问字段,就像在正常情况下一样 class:
scheduledAnnotation.fixedDelay();
在我们的 Spring Boot
应用程序中,我们有一个带有 @Scheduled
注释的方法:
@Scheduled(fixedRate = 1000L * 60 * 10, initialDelay = 1000L * 60 * 5)
public void doSomethingFromTimeToTime(){....}
在我们的 Maven 构建测试阶段,我们希望确保:
- 注释存在(例如,开发人员未错误删除)和
- 包含这些精确值
有没有办法在 unit/integration 测试中以某种方式测试它?或者在构建阶段以另一种方式?
我们不需要测试 Spring 的调度程序本身,只是为了确保注释存在。
我想这样你可以使用反射轻松获得它
Class<?> cls = Class.forName(name);
cls.getDeclaredAnnotations(); // get all annotation
(cls.getDeclaredMethods()[0]).getAnnotations(); //get annotation of a method
Annotation ety = cls.getAnnotation(Annotation.class); // get annotation of particular annotation class
ref How to get the value of annotation using Reflection in Java
您可以使用 Class
的 .getAnnotation(Class<A> annotationType)
方法测试 Class
对象上是否存在注释,其中 A
是泛型类型参数,就像 T
通常是。
用法示例:
Scheduled scheduledAnnotation = MySpringScheduler.class.getAnnotation(Scheduled.class).
获得注解后,您可以使用注解提供的方法访问字段,就像在正常情况下一样 class:
scheduledAnnotation.fixedDelay();