首页 > 解决方案 > Spring AOP - 确定方法是否被@Scheduled调用

问题描述

我有一个运行时注解@MyAnnotation,我想编写一个Aspect 来确定下面的test() 方法是否被以下方法调用:

@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
    }

标签: springaopaspectjspring-aopspring-scheduled

解决方案


也许你想实现这样的目标:

@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;

}

推荐阅读