1. springbooot工程中引入AOP依赖
<dependencies>
<dependency>
<groupId>org.example</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
2. 创建切面类
package com.example.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
@Aspect
@Component
public class LogAspect {
// 定义切点
private final String POINT_CUT = "execution( * com.example.controller.*.*(..))";
// 用于切入点书写简化
@Pointcut(value = POINT_CUT)
public void pt1() {
}
@Before("pt1()")
public void before(JoinPoint joinPoint) {
System.out.println("前置通知:" + joinPoint.getSignature().getName());
}
//可以拿到返回结果,方法正常退出时执行
@AfterReturning(value = "pt1()", returning = "result")
public void afterReturning(JoinPoint joinPoint, Object result) {
System.out.println("后置通知:" + result);
}
//抛出异常会执行此方法
@AfterThrowing(value = "pt1()", throwing = "exception")
public void afterThrowing(JoinPoint joinPoint, Throwable exception) {
System.out.println("异常通知:" + joinPoint.getSignature().getName());
}
// 相当于finally代码块:不管是否抛出异常都会执行
@After(value = "pt1()")
public void after(JoinPoint joinPoint) {
System.out.println("最终通知:" + joinPoint.getSignature().getName());
}
@Around(value = "pt1()")
public Object around(ProceedingJoinPoint proceedingJoinPoint) {
MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
// 获取当前方法对象
Method method = methodSignature.getMethod();
Object obj = null;
try {
System.out.println("环绕通知之前置处理");
obj = proceedingJoinPoint.proceed();
System.out.println("环绕通知之后置处理");
} catch (Throwable throwable) {
System.out.println("环绕通知之异常处理");
}finally {
System.out.println("环绕通知之最终处理");
}
return obj;
}
}
- @Component:将切面类交给容器管理
- @Aspect:标识这是个切面类
- 这里配置了前置、后置、最终、异常、环绕通知
至此,切面已经成功添加到工程中去了