基于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;     }

相关文章
相关标签/搜索