我已經寫了一個註釋(在spring引導應用程序中)並嘗試將其應用於Callable
的call()
方法,但它不起作用,但另一方面,當應用於正常的方法(請參閱下面的代碼),它的工作原理,這一直困擾着我,請你給我一些線索?非常感謝你。Java註釋在Callable上不起作用
這裏是我的代碼,
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LogExecutionTime {
}
@Aspect
@Component
public class LogExecutionTimeAspect {
private static final Logger logger = LoggerFactory.getLogger(LogExecutionTimeAspect.class);
@Around("@annotation(LogExecutionTime)")
public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
final long start = System.currentTimeMillis();
final Object proceed = joinPoint.proceed();
final long executionTime = System.currentTimeMillis() - start;
logger.info(joinPoint.getSignature() + " executed in " + executionTime + "ms");
return proceed;
}
}
public class DummyCallable implements Callable<Integer> {
private Integer start, count;
DummyCallable() {}
DummyCallable(Integer start, Integer count) {
this.start = start;
this.count = count;
}
@LogExecutionTime // not working...
@Override
public Integer call() throws Exception {
Thread.sleep(start * 1000);
Integer sum = 0;
for (Integer i = start; i <= start + count; i++) {
sum += i;
}
return sum;
}
}
@LogExecutionTime // This will work...
public List<Integer> getAllUserScores() {
Callable c1 = new DummyCallable(1, 100000);
Callable c2 = new DummyCallable(2, 100000);
Callable c3 = new DummyCallable(3, 100000);
// .... run them ...
return result;
}
Spring使用代理,只有方法調用INTO對象被攔截,你在內部調用一個方法。 –