繁体   English   中英

Spring Boot AOP不起作用

[英]Spring Boot AOP does not work

我是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 {

}

使用注释@EnableAspectJAutoProxy在App类中启用AspectJ。有关更多信息, 访问: https ://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/EnableAspectJAutoProxy.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM