具有@Scheduled Spring批注的方法的切入点

Rah*_*hul 5 java spring aspectj spring-scheduled

我想为带有方法注释的方法设置AspectJ切入点@Scheduled。尝试了不同的方法,但没有任何效果。

1.)

@Pointcut("execution(@org.springframework.scheduling.annotation.Scheduled * * (..))")
public void scheduledJobs() {}

@Around("scheduledJobs()")
public Object profileScheduledJobs(ProceedingJoinPoint joinPoint) throws Throwable {
    LOG.info("testing")
}
Run Code Online (Sandbox Code Playgroud)

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")
}
Run Code Online (Sandbox Code Playgroud)

任何人都可以提出任何其他方式都around/ before上建议@Scheduled注解的方法?

Bha*_*ikh 6

您正在寻找的切入点可以指定如下:

@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");
    }
}
Run Code Online (Sandbox Code Playgroud)

我不确定这是否是您所需要的。因此,我还将发布解决方案的其他部分。

首先,注意@Aspect类上的注释。此类中的方法需要作为advice.

另外,您需要确保可以@Scheduled通过扫描检测到具有该方法的类。您可以通过使用注释对该类进行注释来做到这一点@Component。例如:

@Component
public class OtherClass {
    @Scheduled(fixedDelay = 5000)
    public void doSomething() {
        System.out.println("Scheduled Execution");
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,要使其正常工作,弹簧配置中所需的部分如下:

<context:component-scan base-package="com.example.mvc" />
<aop:aspectj-autoproxy />   <!-- For @Aspect to work -->    
<task:annotation-driven />  <!-- For @Scheduled to work -->
Run Code Online (Sandbox Code Playgroud)