在使用springboot的时候,要实现一个定时任务的功能非常简单,只要要定时执行的方法上添加@Scheduled注解即可。定时任务相关不是本文内容,本文内容是想使用aop切面记录定时任务执行的开始时间和结束时间。
要使用aop,首先得引入aop的包。在springboot中只要在pom中引入
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
即可,接下来是aop的关键,如何对定时任务切面,即切面的切点是什么。
因为定时任务是使用@Scheduled注解,所以我们可以使用这个注解作为切面的切点。
@Pointcut("@annotation(org.springframework.scheduling.annotation.Scheduled)") public void pointCut(){}
接下来就是记录开始时间和结束时间需要执行的方法,我们使用@Before("pointCut()")和@After("pointCut()")这两个注解即可。
切面类完整代码:
/** * 定时任务切面 */ @Aspect @Component public class TaskAspect { @Pointcut("@annotation(org.springframework.scheduling.annotation.Scheduled)") public void pointCut(){} @Before("pointCut()") public void beforeHandle(JoinPoint joinPoint) { String taskName = getTaskName(joinPoint); System.out.println(DateUtil.now()+" "+taskName+"方法开始----"); } @After("pointCut()") public void afterHandle(JoinPoint joinPoint) { String taskName = getTaskName(joinPoint); System.out.println(DateUtil.now()+" "+taskName+"方法结束----"); } /** * 获取定时任务类加名字 */ private String getTaskName(JoinPoint joinPoint){ return joinPoint.getTarget().getClass().getSimpleName()+"."+joinPoint.getSignature().getName(); } }
运行效果:
项目完整代码:https://gitee.com/lqccan/blog-demo demo6