Pointcut for methods with @Scheduled Spring annotation
Asked Answered
G

1

7

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?

Goldfinch answered 1/6, 2013 at 18:52 Comment(1)
Please use code formatting next time. I have just fixed this, but you have been around here for long enough to have learnt about it. No offense. :-)Corset
I
6

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 -->
Incest answered 2/6, 2013 at 8:57 Comment(1)
This works for Around advice, but I am trying AfterThrowing advice and when my Scheduled job throws an exception it's not intercepted.Tentage

© 2022 - 2024 — McMap. All rights reserved.