问题
I want to have a AspectJ pointcut for methods annotated with @Scheduled
. Tried different approaches but nothing worked.
1.)
@Pointcut("execution(@org.springframework.scheduling.annotation.Scheduled * * (..))")
public void scheduledJobs() {}
@Around("scheduledJobs()")
public Object profileScheduledJobs(ProceedingJoinPoint joinPoint) throws Throwable {
LOG.info("testing")
}
2.)
@Pointcut("within(@org.springframework.scheduling.annotation.Scheduled *)")
public void scheduledJobs() {}
@Pointcut("execution(public * *(..))")
public void publicMethod() {}
@Around("scheduledJobs() && publicMethod()")
public Object profileScheduledJobs(ProceedingJoinPoint joinPoint) throws Throwable {
LOG.info("testing")
}
Can anyone suggest any other way to have around
/before
advice on @Scheduled
annotated methods?
回答1:
The pointcut that you are looking for can be specified as below:
@Aspect
public class SomeClass {
@Around("@annotation(org.springframework.scheduling.annotation.Scheduled)")
public void doIt(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("before");
pjp.proceed();
System.out.println("After");
}
}
I am not sure whether that's all you require or not. So I'm going to post the other parts of the solution as well.
First of all, notice the @Aspect
annotation on the class. It is required for the methods in this class to be applied as advice
.
Also, you need to make sure that the class that has the @Scheduled
method is detectable via scanning. You can do so by annotation that class with @Component
annotation. For ex:
@Component
public class OtherClass {
@Scheduled(fixedDelay = 5000)
public void doSomething() {
System.out.println("Scheduled Execution");
}
}
Now, for this to work, the required parts in your spring configuration would be as follows:
<context:component-scan base-package="com.example.mvc" />
<aop:aspectj-autoproxy /> <!-- For @Aspect to work -->
<task:annotation-driven /> <!-- For @Scheduled to work -->
来源:https://stackoverflow.com/questions/16876117/pointcut-for-methods-with-scheduled-spring-annotation