SpringBoot系列:通过AOP+注解优雅实现操作日志记录
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class OperationLogAspect {
@Pointcut("@annotation(com.example.demo.annotation.OperationLog)")
public void operationLogPointcut() {
}
@Before("operationLogPointcut() && @annotation(operationLog)")
public void doBefore(JoinPoint joinPoint, OperationLog operationLog) {
// 在此处编写操作日志的记录逻辑
// 例如,可以获取操作的详细信息:
String className = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
// 使用这些信息进行日志记录
System.out.println("Operation Log: Before operation " + methodName + " in " + className);
}
@AfterReturning(pointcut = "operationLogPointcut()", returning = "result")
public void doAfterReturning(Object result) {
// 在此处编写操作日志的记录逻辑
System.out.println("Operation Log: After operation returning: " + result);
}
// 可以添加更多的通知方法,如@AfterThrowing等
}
这个示例代码展示了如何使用Spring AOP和自定义注解来记录操作日志。在doBefore
方法中,我们可以获取被注解标记的方法的详细信息,并记录操作的开始。在doAfterReturning
方法中,我们记录操作的返回结果。这种方式使得日志记录的代码与业务逻辑代码解耦,提高了代码的可维护性和可读性。
评论已关闭