码迷,mamicode.com
首页 > 其他好文 > 详细

自定义注解的应用

时间:2016-10-18 22:23:32      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:

     在项目中经常会用到自定义注解,下面列举二个使用自定义注解的案例。

一、利用自定义注解打印接口调用时长日志

#创建ServiceLog类用来自定义注解
@Retention(RetentionPolicy.Runtime)
@Target(ElementType.METHOD)
public @interface ServiceLog {

}

#定义ServiceLogAspect类用来定义日志打印信息

@Component
@Aspect 
public class ServiceLogAspect {

   public ThreadLocal<Long> local = new ThreadLocal<Long>();
   
   @Pointcut("@annotation(com.test.XXX.ServiceLong)")
   public void pointCut() {
    
   } 

   @Before("pointCut()")
   public void before(JoinPoint point) {
    String methodName = point.getTarget().getClass().getName()+"."+point.getSignature().getName();
    local.set(System.currentTimeMillis());
   }

  @After("pointCut()")
   public void after(JoinPoint point) {
    long start = local.get();
    String methodName = point.getTarget().getClass().getName()+"."+point.getSignature().getName();
    System.out.println(System.currentTimeMillis()-start));
    }
   
  @AfterThrowing(pointcut="pointCut()",throwing="error")
   public void throwing(JoinPoint point,Throwable error) {
    System.out.println("error");
    }

}

 完成上述定义,如果需要记录方法调用时长时,可以直接使用@ServiceLog注解。

自定义注解的应用

标签:

原文地址:http://www.cnblogs.com/moonandstar08/p/5975156.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!