我是Spring Boot和AOP的新手,过去三天我一直试图让这个工作无效。
我有一个名为App的课程。此类调用一个名为invokeRetrieveMethod的方法 - 该方法调用自动装配的businessClass对象中的另一个方法。我只是尝试记录运行使用我的自定义@LogExecutionTime
注释注释的方法所花费的时间,但是在运行我的代码时我得到一个空指针异常。请帮忙!
@SpringBootApplication
public class App
{
@Autowired
BusinessClass businessClass;
public static void main( String[] args )
{
SpringApplication.run(App.class, args);
System.out.println("Starting application...");
App app = new App();
app.invokeRetrieveSomething();
}
public void invokeRetrieveSomething() {
businessClass.retrieveSomething();
}
}
Spring boot" bean"(?)
@Component
public class BusinessClass {
@LogExecutionTime
public void retrieveSomething() {
System.out.println("This is the retrieveSomething() method.");
}
}
我的看点
@Aspect //specifies that this is an aspect
@Component //because we want this class to be turned into a bean in order for it to work supposedly
public class ExampleAspect {
@Around("@annotation(LogExecutionTime)")
public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
long start = System.currentTimeMillis(); //executed before the method annotated with @LogExecutionTime is executed.
Object proceed = joinPoint.proceed();
//everything below gets executed after the method.
long executionTime = System.currentTimeMillis() - start;
System.out.println(joinPoint.getSignature() + " executed in " + executionTime + "ms");
return proceed;
}
}
我的自定义注释
@Target(ElementType.METHOD) //tells us *where* this annotation will be applicable (ElementType.METHOD means on methods only)
@Retention(RetentionPolicy.RUNTIME) //states whether the annotation will be available to the jvm at runtime or not. by default, it's not.
public @interface LogExecutionTime {
}
答案 0 :(得分:-1)
使用注释@EnableAspectJAutoProxy在App类中启用AspectJ 详情请见:https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/EnableAspectJAutoProxy.html