Spring Boot AOP не работает
Я новичок в 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();
}
}
Весенний ботинок "боб"(?)
@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 {
}
1 ответ
Включите AspectJ в классе App, используя аннотацию @EnableAspectJAutoProxy. Дополнительная информация: https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/EnableAspectJAutoProxy.html