【发布时间】:2018-02-08 05:59:39
【问题描述】:
我正在使用这个自定义注解来记录执行时间,注解可以出现在所有公共方法都有它的方法或类上。一切正常,除非方法级别“LogExecutionTime logExecutionTime”为空。这会引发 NPE。
@Around("@annotation(logExecutionTime) || @within(logExecutionTime)")
public Object logExecutionTime(ProceedingJoinPoint joinPoint, LogExecutionTime logExecutionTime) throws Throwable {
final Logger logger = LoggerFactory.getLogger(joinPoint.getTarget().getClass());
final String name = joinPoint.toShortString();
final StopWatch stopWatch = new StopWatch(name);
stopWatch.start(name);
try {
return joinPoint.proceed();
} finally {
stopWatch.stop();
if (logExecutionTime.value()) {
logger.info(joinPoint.getSignature().getName() + ".time=", stopWatch.getTotalTimeSeconds());
}
}
}
如果我颠倒顺序-
@Around("@within(logExecutionTime) || @annotation(logExecutionTime)")
行为相反,我在方法级别获得了一个有效对象,在类级别注释方法获得了 null。
我已经通过使用 2 个显式方法并将两者分开来解决这个问题 -
@Around("@within(logExecutionTime)")
public Object logExecutionTimeClassLevel(ProceedingJoinPoint joinPoint, LogExecutionTime logExecutionTime) throws Throwable {
return logExecutionTimeMethodLevel(joinPoint, logExecutionTime);
}
@Around("@annotation(logExecutionTime)")
public Object logExecutionTimeMethodLevel(ProceedingJoinPoint joinPoint, LogExecutionTime logExecutionTime) throws Throwable {
final Logger logger = LoggerFactory.getLogger(joinPoint.getTarget().getClass());
final String name = joinPoint.toShortString();
final StopWatch stopWatch = new StopWatch(name);
stopWatch.start(name);
try {
return joinPoint.proceed();
} finally {
stopWatch.stop();
if (logExecutionTime.value()) {
logger.info(joinPoint.getSignature().getName() + ".time=", stopWatch.getTotalTimeMillis());
}
}
希望了解这种行为,当我们使用 OR '||'有两个切入点。
班级水平
@LogExecutionTime
@Component
public class CleanUpService implements ICleanUpService { ... }
方法层
@Scheduled(fixedDelay = 100)
@LogExecutionTime(false)
public void processMessageQueue() { ... }
【问题讨论】:
-
您能否与我们分享您的目标方法和注释的实现,以便我可以重现您的用例
-
@elmehdi 请立即查看
标签: java spring spring-boot annotations spring-aop