AOP+自定义注解+反射实现操作日志修改前数据和修改后数据

2022-10-30 11:45:47

AOP+自定义注解+反射实现操作日志修改前数据和修改后数据

1.自定义注解

2. 进行aop切面

@Aspect
@Component
public class LogAspect {

    private Logger logger = LoggerFactory.getLogger(LogAspect.class);
    @Autowired
    private LogService logService;
    @Pointcut(value = "@annotation(com.ylzinfo.apps.annotation.SysLog)")
    public void logAnnotation() {
    }
    @Around(value = "logAnnotation()&& @annotation(sysLog)")
    public Object around(ProceedingJoinPoint point,SysLog sysLog) throws Exception {
        logger.info("开始切面!");
        //获取方法参数
        MethodSignature signature = (MethodSignature) point.getSignature();
        //获取操作类型
        String operationType = sysLog.operationType();
        //获取业务类型
        String ywlx = sysLog.ywlx();
        //修改之前的数据
        Object beforeJson=new Object();
        Object result=null;
        if("update".equals(operationType)){
            Object[] args = point.getArgs();
            Object arg = args[0];
            String s = JSONObject.toJSONString(arg);
            JSONObject afterJson = JSONObject.parseObject(s);
            String id = afterJson.get(sysLog.id()).toString();
            String className = point.getSignature().getDeclaringTypeName();   //被代理的类名
            Class<?> daoClass = Class.forName(className);
            Object  o =  point.getTarget();
//通过反射机制实现查询方法
            Method method = daoClass.getDeclaredMethod("selectByPrimaryKey", String.class);
            Object invoke = method.invoke(o, id);
            String oldJson = JSONObject.toJSONString(invoke);
       
            try {
                //执行方法
                result = point.proceed(args);
            } catch (Exception e) {
                throw e;
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
            //创建一个日志对象接收参数
            Twtpzj_log log = new Twtpzj_log();
            log.setBeforeupdate(oldJson);
            log.setAfterupdate(afterJson.toJSONString());
            log.setType(operationType);
            log.setYwlx(ywlx);
            logService.insertSelective(log);
        }
        return result;
    }

}

3.在web.xml中 找到spring配置文件 ,让扫描注解bean扫描到刚刚加入的注解

把切面所在的类加入到springmvc 配置文件中。

 3.注解调用

  • 作者:蓦然回首已经是秃头
  • 原文链接:https://blog.csdn.net/qq_31439313/article/details/108995730
    更新时间:2022-10-30 11:45:47