通过自定义注解利用AOP在springmvc中实现记录日志

来源:互联网 发布:淘宝审核不通过怎么办 编辑:程序博客网 时间:2024/06/05 11:53

项目中需要记录用户操作日志,本文讲解使用的一种方法


1、导入所需jar包

除了spring相关jar包外,还需要引入aspectj包。


2、在配置文件中配置

在springmvc-servlet.xml中实现对AOP的支持

<aop:aspectj-autoproxy proxy-target-class="true"/>


3、自定义注解

@Retention(RetentionPolicy.RUNTIME)@Target({ ElementType.METHOD })public @interface Log {    String name() default "";}
根据记录日志的需求定义自己需要注解的属性


4、编写记录日志的类——最主要的

需要添加@Aspect注解

@Aspect@Componentpublic class LogAop_2 {    ThreadLocal<Long> time=new ThreadLocal<Long>();    ThreadLocal<String> tag=new ThreadLocal<String>();         @Pointcut("@annotation(Log)")//这地方也可以使用execution表达式匹配方法    public void log(){        System.out.println("我是一个切入点");    }         /**     * 在所有标注@Log的地方切入     * @param joinPoint     */    @Before("log()")    public void beforeExec(JoinPoint joinPoint){               time.set(System.currentTimeMillis());        tag.set(UUID.randomUUID().toString());                 info(joinPoint);                 MethodSignature ms=(MethodSignature) joinPoint.getSignature();        Method method=ms.getMethod();        System.out.println(method.getAnnotation(Log.class).name()+"标记"+tag.get());    }         @After("log()")    public void afterExec(JoinPoint joinPoint){        MethodSignature ms=(MethodSignature) joinPoint.getSignature();        Method method=ms.getMethod();        System.out.println("标记为"+tag.get()+"的方法"+method.getName()+"运行消耗"+(System.currentTimeMillis()-time.get())+"ms");    }         @Around("log()")    public void aroundExec(ProceedingJoinPoint pjp) throws Throwable{        System.out.println("我是Around,来打酱油的");        pjp.proceed();    }         private void info(JoinPoint joinPoint){        System.out.println("King:\t"+joinPoint.getKind());        System.out.println("Target:\t"+joinPoint.getTarget().toString());        Object[] os=joinPoint.getArgs();        System.out.println("Args:");        for(int i=0;i<os.length;i++){            System.out.println("\t==>参数["+i+"]:\t"+os[i].toString());        }        System.out.println("Signature:\t"+joinPoint.getSignature());        System.out.println("SourceLocation:\t"+joinPoint.getSourceLocation());        System.out.println("StaticPart:\t"+joinPoint.getStaticPart());        System.out.println("--------------------------------------------------");    }  }

  1. @Before – 目标方法执行前执行

  2. @After – 目标方法执行后执行

  3. @AfterReturning – 目标方法返回后执行,如果发生异常不执行

  4. @AfterThrowing – 异常时执行

  5. @Around – 在执行上面其他操作的同时也执行这个方法


5、在需要记录用户操作日志的方法上添加注解@Log,即可记录用户对该方法的操作


说明:如果不想自定义注解也是可以的,即第三步不是必须的。

则在第四步,定义切入点Pointcut的时候就不能使用@annotation,

要使用execution表达式配置需要记录日志的方法

请根据个人喜好和需要进行选择!!!


让我们一起遨游在代码的海洋里!

0 1
原创粉丝点击