Spring AOP 可以通过切面来实现日志记录。在 Spring AOP 中,可以定义一个切面(Aspect),并在该切面中定义通知(Advice),在通知中编写日志记录的逻辑。
以下是一个简单的示例:
@Aspect
@Component
public class LogAspect {
private static final Logger logger = LoggerFactory.getLogger(LogAspect.class);
@Before("execution(* com.example.service.*.*(..))")
public void logBefore(JoinPoint joinPoint) {
logger.info("Method executed: " + joinPoint.getSignature());
}
@AfterReturning(pointcut = "execution(* com.example.service.*.*(..))", returning = "result")
public void logAfterReturning(JoinPoint joinPoint, Object result) {
logger.info("Method returned: " + result);
}
@AfterThrowing(pointcut = "execution(* com.example.service.*.*(..))", throwing = "exception")
public void logAfterThrowing(JoinPoint joinPoint, Throwable exception) {
logger.error("Method threw exception: " + exception.getMessage());
}
}
<aop:aspectj-autoproxy/>
@Service
public class ExampleService {
public void doSomething() {
// Code here
}
}
通过以上步骤,Spring AOP 就可以实现日志记录功能。在调用 ExampleService 类中的方法时,LogAspect 中定义的通知方法会被触发,记录方法执行前、执行后返回值以及异常信息。