基於Spring AOP的日誌管理

1. Spring AOP + 註解 實現攔截(包括Controller層的攔截) -spring

  • 定義註解

@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LogAnnotation {數組

    String remark() default "操做日誌記錄";mvc

app

注意:在Spring的主配置文件配置組件掃描 ``` ``` -ui

  • 定義AOP攔截器

@Component
@Aspect
public class LogAspect implements Serializable {this

    private static final long serialVersionUID = 1L;.net

    //定義攔截的方法代理

    @Pointcut("@annotation(com.emvc.aspect.LogAnnotation)")
    public void methodCachePointcut() {日誌

    }code

    //攔截處理

    @After("methodCachePointcut()  && @annotation(logRemark)")
    public void doAfter(JoinPoint jp, LogAnnotation logRemark) throws ClassNotFoundException, NotFoundException {

          //業務處理

    }

注:要在spring的配置文件配置, 特別的Controller的代理默認是JDK,若是想要用AOP攔截Controller的方法,須要將Controller的代理交由Cglib(在Spring mvc的配置文件配置 ),expose-proxy將Controller代理交由Cglib。

2.AOP攔截後的參數處理(利用反射獲取方法的參數名及其值)

    /**
    *    返回  參數名=值;
    **/
    private static String writeLogInfo(String[] paramNames, JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        StringBuilder sb = new StringBuilder();
        for (int k = 0; k < args.length; k++) {
            Object arg = args[k];
            sb.append(paramNames[k]);
            sb.append("=" + arg + ";");
        }
        return sb.toString();
    }

    /**      * 獲得方法參數的名稱      *       * @param cls  this.getClass(),       * @param clazzName jp.getTarget().getClass().getName()      * @param methodName jp.getSignature().getName()      * @return 參數名數組      * @throws NotFoundException      */     private String[] getFieldsName(Class cls, String clazzName, String methodName) throws NotFoundException {         ClassPool pool = ClassPool.getDefault();         ClassClassPath classPath = new ClassClassPath(cls);         pool.insertClassPath(classPath);                  CtClass cc = pool.get(clazzName);         CtMethod cm = cc.getDeclaredMethod(methodName);         MethodInfo methodInfo = cm.getMethodInfo();         CodeAttribute codeAttribute = methodInfo.getCodeAttribute();         LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);         if (attr == null) {             return null;         }         String[] paramNames = new String[cm.getParameterTypes().length];         int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;         for (int i = 0; i < paramNames.length; i++) {             paramNames[i] = attr.variableName(i + pos); // paramNames即參數名         }         return paramNames;     }

相關文章
相關標籤/搜索