papa1. 引入依赖
<!-- aop-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2.创建切面
@Component
@Aspect
@Slf4j
public class AopAspect {
}
3.创建切点
可以定义get post方法 也可以定义普通的方法
第一个 * 代表返回值
.*代表方法名
(..)代表随意参数也可以指定类型
@Pointcut("@annotation(org.springframework.web.bind.annotation.GetMapping)")
public void getLog(){}
@Pointcut("@annotation(org.springframework.web.bind.annotation.PostMapping)")
public void postLog(){}
@Pointcut("execution(* com.example.aa.service.test.*(..))")
public void sum(){}
@Pointcut("execution(* com.example.aa.service.test.*(int))")
@Pointcut("execution(* com.example.aa.service.test.*(com.example.User))")
@Pointcut("execution(* com.example.aa.service.test.*(java.lang.String))")
4.创建通知
可以通过参数获得方法名,参数等,也可以通过request获得请求的url,类型等
@Before("sum() || postLog()")
public void bf(JoinPoint point){
//获得方法名
String name = point.getSignature().getName();
//获得参数
Object[] args = point.getArgs();
String s = Arrays.toString(args);
//使用log日志
log.info("日志输出")
System.out.println("执行前置通知"+name+s);
}
环绕通知通过这个方法 joinPoint.proceed() 执行原方法 返回值为obj
@Around("execution(* com.example.service.*.*(..))")
public Object handleException(ProceedingJoinPoint joinPoint) throws Throwable {
try {
return joinPoint.proceed();
} catch (Exception e) {
// 在这里处理异常,例如记录日志、进行补偿操作等
System.out.println("Exception occurred in method: " + joinPoint.getSignature().getName() + ", Message: " + e.getMessage());
// 您可以根据需要抛出一个自定义的异常,或者返回一个默认值
throw new CustomException("An error occurred while processing the method.");
}
}
抛出异常后通知
@Around("execution(* com.example.service.*.*(..))")
public Object handleException(ProceedingJoinPoint joinPoint) throws Throwable {
try {
return joinPoint.proceed();
} catch (Exception e) {
// 在这里处理异常,例如记录日志、进行补偿操作等
System.out.println("Exception occurred in method: " + joinPoint.getSignature().getName() + ", Message: " + e.getMessage());
// 您可以根据需要抛出一个自定义的异常,或者返回一个默认值
throw new CustomException("An error occurred while processing the method.");
}
}