标签:
在项目中经常会用到自定义注解,下面列举二个使用自定义注解的案例。
一、利用自定义注解打印接口调用时长日志
#创建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