应用场景
在某些业务接口中需要鉴权或者日志记录或者其他的一些公共的事项。比如需要计算指定某些接口的耗时情况,一般的做法是在每个接口中都加上计算接口耗时的逻辑,这样各个接口中就会有这样重复计算耗时的逻辑,这样会有很多重复代码。 通过自定义注解和AOP的方式可以轻松的解决代码重复的问题。
自定义注解
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TimeCost {
}
定义切面实现类
@Aspect
@Component
public class CostTimeAspect {
Logger log = LoggerFactory.getLogger(CostTimeAspect.class);
@Pointcut(value = "@annotation(com.au.sa.oa.sale.services.TimeCost)")//自定义注解的类路径
public void costTime(){ }
@Around("costTime()")
public Object costTimeAround(ProceedingJoinPoint joinPoint) {
Object obj = null;
try {
long beginTime = System.currentTimeMillis();
obj = joinPoint.proceed();
//获取方法名称
String method = joinPoint.getSignature().getName();
//获取类名称
String className = joinPoint.getSignature().getDeclaringTypeName();
//计算耗时
long cost = System.currentTimeMillis() - beginTime;
log.info("类:[{}],方法:[{}] 接口耗时:[{}]", className, method, cost + "毫秒");
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return obj;
}
}