使用spring aop + 注解完成对业务操作的日志记录

来源:互联网 发布:淘宝卖家主营占比 编辑:程序博客网 时间:2024/06/04 23:37

话不多说直接上代码,不喜勿喷@After("@annotation(com.你的路径.service.LogAntn)")    public void afterAdvice(JoinPoint joinPoint) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException{Object[] args = joinPoint.getArgs();User user = null;Map<String, String> paramsMap = null;for (Object object : args) {if(object instanceof User){user = (User)object;}else if(object instanceof Map){paramsMap = (Map<String, String>)object;}}LogAntn logAntn = getAntn(joinPoint);String signature = joinPoint.getSignature().toString(); // 获取目标方法签名          String methodName = signature.substring(signature.lastIndexOf(".") + 1,signature.indexOf("("));  String clazzName = joinPoint.getTarget().getClass().getName();Class<?> clazz = Class.forName(clazzName);Method[] methods = clazz.getDeclaredMethods(); for (Method method : methods) {               if (method.isAnnotationPresent(LogAntn.class)&& method.getName().equals(methodName)) {                 opObj opObjType = logAntn.opObjType();                 String objVal = opObjType.getValue();//操作对象                 opType type = logAntn.type();                 String opVal = type.getValue();//操作类型//添加入库操作             }           }          logger.info("aop log ... this is after Advice......");    }
@Documented@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface LogAntn {enum opType{//UPDATE,ADD,DELETE,REPORT,SEND,TURNEDDOWNUPDATE("UPDATE","修改/维护"),DEL("DEL","删除/撤销"),ADD("ADD","添加");private String key;private String value;private opType(String key,String value) {this.key = key;this.value = value;}public String getKey(String key){return key;}public String getValue() {        return value;    }};opType type();enum opObj{//操作的简单描述REPORT("REPORT","上报审批");};opObj opObjType();}

//获取注解public static LogAntn getAntn(JoinPoint joinPoint){Signature signature = joinPoint.getSignature();          MethodSignature methodSignature = (MethodSignature) signature;          Method method = methodSignature.getMethod();         if (method != null) {              return method.getAnnotation(LogAntn.class);          }          return null;}


1 0
原创粉丝点击