SpringBootWeb 篇-深入了解 AOP 面向切面编程与 AOP 记录操作日志案例
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class LoggingAspect {
private static final Logger logger = LoggerFactory.getLogger(LoggingAspect.class);
@Pointcut("execution(* com.example.demo.controller..*.*(..))")
public void controllerLogging(){}
@Before("controllerLogging()")
public void doBefore(JoinPoint joinPoint) {
logger.info("Method: " + joinPoint.getSignature().getName());
}
@AfterReturning(pointcut = "controllerLogging()", returning = "result")
public void doAfterReturning(Object result) {
logger.info("Result: " + result);
}
@AfterThrowing(pointcut = "controllerLogging()", throwing = "e")
public void doAfterThrowing(Exception e) {
logger.error("Exception: " + e.getMessage());
}
@Around("controllerLogging()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
logger.info("Entering method: " + joinPoint.getSignature().getName());
Object result = joinPoint.proceed();
logger.info("Exiting method: " + joinPoint.getSignature().getName());
return result;
}
}
这段代码定义了一个日志切面,用于记录 Spring Boot 控制层(com.example.demo.controller
包及其子包中的所有方法)的操作日志。它使用了@Pointcut
注解来定义一个切点,即要被日志切面处理的方法。然后,它使用了@Before
、@AfterReturning
、@AfterThrowing
和@Around
注解来定义不同类型的通知。这些通知方法会在目标方法执行前、执行后以及出现异常时被调用,从而实现了日志记录的功能。
评论已关闭