AOP|Spring AOP面向切面编程之日志记录

【AOP|Spring AOP面向切面编程之日志记录】实际项目中我们往往需要将一些重要的操作,以日志的形式进行保存,当机器宕机的时候,可以通过查找日志,定位出错位置,方便恢复。
1:首先导入spring支持的AOP架包
2:编写将要进行切面工作的类

/** * */ package com.zhiyou100.aspect; import java.util.Arrays; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.springframework.stereotype.Component; /** * @author Administrator * */ @Aspect @Component public class LoggingAspect { //前置通知 public void beforeMethod(JoinPoint joinPoint) { String methodName = joinPoint.getSignature().getName(); Object[] args = joinPoint.getArgs(); long timeMillis = System.currentTimeMillis(); System.out.println("start execute time:" + timeMillis + "," + methodName + " start execute,args:" + Arrays.toString(args)); } //最终通知 public void afterMethod(JoinPoint joinPoint) { String methodName = joinPoint.getSignature().getName(); long times = System.currentTimeMillis(); System.out.println("after execute time:" + times + "," + methodName + " execute end"); } //后置通知 public void afterReturning(JoinPoint joinPoint, Object result) { String methodName = joinPoint.getSignature().getName(); System.out.println(methodName + " execute result:" + result); } //异常通知 public void afterThrowing(JoinPoint joinPoint, Exception e) { String methodName = joinPoint.getSignature().getName(); System.out.println(methodName + " execute exception:" + e); }}

3:纳入spring容器

4:最好是在log4j.properties里面配置日志保存地址为我们的本地,实际开发中,日志保存在集群中,并且是以天为单位进行动态滚动进行保存的。

    推荐阅读