SpringBoot中使用AspectJ

时间:2025-05-15 17:39:17
package sb.simple.aspectj.normal; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import org.springframework.context.annotation.Configuration; import java.util.Arrays; /** * AspectJ * 五种通知注解:@Before/@Around/@After/@AfterReturning/@AfterThrowing */ @Configuration @Aspect public class AJNormal { @Pointcut("execution(* .*.*(..))") public void point() { } /** * 前置通知 * 连接点之前执行 */ @Before("point()") public void before(JoinPoint joinPoint) { String methodName = joinPoint.getSignature().getName(); Object[] args = joinPoint.getArgs(); System.out.println("before() methodName:" + methodName + ", args:" + Arrays.toString(args)); } @Around("point()") public Object around(ProceedingJoinPoint joinPoint) throws Throwable { String methodName = joinPoint.getSignature().getName(); Object[] args = joinPoint.getArgs(); System.out.println("around() before proceed"); Object proceed = joinPoint.proceed(); System.out.println("around() after proceed methodName:" + methodName + ", args:" + Arrays.toString(args) + ", result:" + proceed); return proceed; } /** * 后置通知 * 连接点方法完成后执行 * 无论连接点执行成功与否该通知都会执行 */ @After("point()") public void after(JoinPoint joinPoint) { String methodName = joinPoint.getSignature().getName(); Object[] args = joinPoint.getArgs(); System.out.println("after() methodName:" + methodName + ", args:" + Arrays.toString(args)); } /** * 连接点方法执行成功后执行 * 可以拿到返回结果 */ @AfterReturning(value = "point()", returning = "result") public void result(JoinPoint joinPoint, Object result) { String methodName = joinPoint.getSignature().getName(); Object[] args = joinPoint.getArgs(); System.out.println("AfterReturning() methodName:" + methodName + ", args:" + Arrays.toString(args) + ", result:" + result); } /** * 连接点方法执行异常后执行 * 可以拿到异常信息 */ @AfterThrowing(value = "point()", throwing = "exception") public void afterThrowing(JoinPoint joinPoint, Exception exception) { String methodName = joinPoint.getSignature().getName(); Object[] args = joinPoint.getArgs(); System.out.println("afterThrowing() methodName:" + methodName + ", args:" + Arrays.toString(args) + ", exception:" + exception); } }