基于Spring AOP的日志管理

1. Spring AOP + 注解 实现拦截(包括Controller层的拦截) -

  • 定义注解

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

    String remark() default "操作日志记录";

注意:在Spring的主配置文件配置组件扫描 ``` ``` -

  • 定义AOP拦截器

@Component
@Aspect
public class LogAspect implements Serializable {

    private static final long serialVersionUID = 1L;

    //定义拦截的方法

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

    }

    //拦截处理

    @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;
    }

转载于:https://my.oschina.net/u/2307114/blog/712562

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值