注意 @AfterReturning 和 @AfterThrowing 的用法,一个用来对返回值进行处理,
一个对异常进行处理
@Slf4j
@Aspect
@Component
public class ControllerAspect {
@Pointcut(value = "execution(* com.magic.platform.business.*.controller..*.*(..))")
public void controllerMethod() {}
/**
* 方法执行前
* @param jp
*/
@Before("controllerMethod()")
public void controllerMethodBefore(JoinPoint jp) {
try {
String targetClassName = jp.getTarget().getClass().getName();
String methodName = jp.getSignature().getName();
String args = Arrays.toString(jp.getArgs());
// 获取代理目标类自己的 logger
Logger logger = LoggerFactory.getLogger(targetClassName);
logger.info(">>>:{}.{}({}) begin", targetClassName, methodName, args.substring(1, args.length() - 1));
} catch (Exception e) {
log.error("ControllerAspect.controllerMethodBefore exception:", e);
}
}
/**
* 方法执行后
* @param jp
*/
@After("controllerMethod()")
public void controllerMethodAfter(JoinPoint jp) {
try {
String targetClassName = jp.getTarget().getClass().getName();
String methodName = jp.getSignature().getName();
String args = Arrays.toString(jp.getArgs());
// 获取代理目标类自己的 logger
Logger logger = LoggerFactory.getLogger(targetClassName);
logger.info(">>>:{}.{}({}) end", targetClassName, methodName, args.substring(1, args.length() - 1));
} catch (Exception e) {
log.error("ControllerAspect.controllerMethodAfter exception:", e);
}
}
/**
* 方法异常处理 FIXME: 注意避免与 ExceptionHandler 重复处理异常
* @param jp
* @param exception
*/
@AfterThrowing(value = "controllerMethod()", throwing = "exception")
public void controllerMethodAfterThrowing(JoinPoint jp, Throwable exception) {
try {
String targetClassName = jp.getTarget().getClass().getName();
String methodName = jp.getSignature().getName();
String args = Arrays.toString(jp.getArgs());
// 获取代理目标类自己的 logger
Logger logger = LoggerFactory.getLogger(targetClassName);
logger.info(">>>:{}.{}({}) exception: {}", targetClassName, methodName, args.substring(1, args.length() - 1), exception.getMessage());
} catch (Exception e) {
log.error("ControllerAspect.controllerMethodAfter exception:", e);
}
}
/**
* 方法返回
* @param joinPoint
* @param object
*/
@AfterReturning(value = "controllerMethod()", returning = "object")
public void controllerMethodAfterReturning(JoinPoint joinPoint, Object object) {
// 使用 RequestContextHolder 获取 request
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
if (object instanceof ResponseModel) {
((ResponseModel) object).setTimestamp(new Date());
((ResponseModel) object).setPath(request.getRequestURI());
}
}
// @Around("controllerMethod()")
// public void controllerMethodAround(ProceedingJoinPoint jp) {
//
// }
}
切点的写法:切一个类中的所有的方法
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
日志注解,aop 需要引用的 jar 包
网友评论