spring - Spring AOP - 确定方法是否被@Scheduled调用
问题描述
我有一个运行时注解@MyAnnotation,我想编写一个Aspect 来确定下面的test() 方法是否被以下方法调用:
- Spring 的 @Scheduled 框架
- 正常的方法调用
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
@Scheduled(cron = "*/1 * * * * *") // scheduled to invoke every second
@MyAnnotation
public void test() {
// business logic
}
}
方面代码(切入点+建议)
@Around(value="@annotation(myAnnotation)")
public Object featureToggle(ProceedingJoinPoint joinPoint, MyAnnotation myAnnotation) throws Throwable {
Boolean isInvoked = // TODO - is invoked by @Scheduled or not
}
解决方案
也许你想实现这样的目标:
@Slf4j
@Component
public class ScheduledTask {
@Scheduled(cron = "0/1 * * * * *")
@ScheduledTaskAnnotation(message = "ScheduledTaskMessage", number = 10)
public void doAction() {
log.debug("Task scheduled");
}
}
@Slf4j
@Aspect
@Component
public class ScheduledTaskAspect {
@Around("execution(public * *(..)) && @annotation(hu.gaszabo.sample.schedule.ScheduledTaskAnnotation)")
public void logScheduledTaskAction(final ProceedingJoinPoint p) {
log.debug("Aspect");
parameters(p).ifPresent(a -> {
log.debug("message: {}", a.message());
log.debug("number: {}", a.number());
});
try {
p.proceed();
} catch (Throwable e) {
e.printStackTrace();
}
}
private Optional<ScheduledTaskAnnotation> parameters(final ProceedingJoinPoint p) {
final Method method = ((MethodSignature) p.getSignature()).getMethod();
return Optional.ofNullable(AnnotationUtils.findAnnotation(method, ScheduledTaskAnnotation.class));
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target(value = { ElementType.METHOD })
public @interface ScheduledTaskAnnotation {
String message() default "Message";
long number() default 0L;
}
推荐阅读
- go - 正确等待全局变量初始化
- ios - iOS: How to set the device serial number via application configuration in airwatch?
- sql - Select value from lower rank when null
- android - Google play 排行榜只显示我
- c# - Bellmanford in C# : Always returns negative cycle. Am I missing somthing?
- google-apps-script - 在 Google Apps Script Web App 中传递和使用参数
- sql - PostgreSQL中的for循环调用API
- angular - 在 Angular 5 中观察一个函数
- html - CSS Flexbox 布局 - 3 列和 2 列互换
- python - 从 MongoDB 获取数据后,如何在将数据推送到 Kafka 的同时加快 Kafka 的速度?