Spring中使用Annotation来记录方法的运行时间

在Spring的Java程序中,每个方法写一句log来记录这个方法执行多久是一件很恶心的事情。记录下使用annotation来解决。

1. 定义一个annotation

@Target({java.lang.annotation.ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LogExecuteTime {

}

2. 然后写一个Aspect:

@Aspect
@Component
public class LogTimeInterceptor {
	
	private static Logger logger = LoggerFactory.getLogger(LogTimeInterceptor.class);
	
	@Pointcut("@annotation(com.xxx.quartz.cluster.annotation.LogExecuteTime)")
	public void logTimeMethodPointcut() {
		
	}
	
	@Around("logTimeMethodPointcut()")
	public Object interceptor(ProceedingJoinPoint pjp) {
		long startTime = System.currentTimeMillis();
		
		Object result = null;
		try {
			result = pjp.proceed();
		} catch (Throwable e) {
			logger.error(e.getMessage(), e);
			throw new RuntimeException(e);
		}
		
		logger.info(pjp.getSignature().getDeclaringTypeName() + "." + pjp.getSignature().getName() + " spend " + (System.currentTimeMillis() - startTime) + "ms");
		
		return result;
	}

}

3. 在需要记录执行时间的方法上加上这个annotation:

	@LogExecuteTime
	public long myMethod(List<Integer> keys) {
		return xxx;
	}

运行以后我们就能在log中看到了这个类的这个方法执行了多久。。如果还需要加其它参数,请修改上面的interceptor方法。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值