问题描述
我试图拦截带注释的方法的执行以记录执行时间;所以我创建了一个新注释:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LogExecutionTime {
}
我将注释应用到要跟踪的方法上(方法的类未注释,例如@Service或@Component;这有问题吗?):
@LogExecutionTime
public void execute() throws Exception {
...
}
然后创建类和@Around方法:
@Aspect
@Component
public class PerformanceAnnotation {
@Around("@annotation(LogExecutionTime)")
public void logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
Logger logger = getClassLogger(joinPoint);
logger.info("Started method " + joinPoint.getSignature().getName() + " of class " + joinPoint.getTarget().getClass());
long start = System.currentTimeMillis();
joinPoint.proceed();
long executionTime = System.currentTimeMillis() - start;
logger.info("Execution time (millis): " + executionTime);
}
}
然后在pom中添加spring-boot-starter-aop依赖项,并将@EnableAspectJAutoproxy添加到主类(@SpringBootApplication注释为一个)。 我希望当我调用execute()方法时,首先调用方法logExecutionTime()(用@Around注释的方法)。但事实并非如此。有什么建议?谢谢
解决方法
我将注释应用到要跟踪的方法上(方法的类未注释,例如
class_mode='binary'
或@Service
;这有问题吗?):
是的。 Spring无法将AOP应用于他不知道的课程。我尝试了您的代码,并且如果用@Component
注释的方法在用@LogExecutionTime
(或@Service
...)注释的类中,则可以使用。