在 Controller class 中使用自定义注释时自动装配不起作用

Autowiring not working when using Custom annotations in Controller class

我尝试为记录方法执行时间创建一个自定义注释,它工作正常,直到我在不在控制器中的方法上使用注释 class。当在控制器 class 中使用时,其他 class(服务 class)的自动装配失败并给出空指针异常。

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LogExecutionTime {
}

--

@Aspect
@Component
public class ExampleAspect {

    @Around("@annotation(LogExecutionTime)")
    public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
        long start = System.currentTimeMillis();

        Object proceed = joinPoint.proceed();

        long executionTime = System.currentTimeMillis() - start;

        System.out.println(joinPoint.getSignature() + " executed in " + executionTime + "ms");
        return proceed;
    }

}

当我在控制器以外的任何 class 上使用此注释时,它工作正常。

@RestController
public class ProjectController {

    @Autowired
    ProjectService projectService;

    @GetMapping("/testTimeTaken")
    @LogExecutionTime
    private String testTimeTaken() {
        return projectService.dummyMethod();
    }

}

您不能使用方面来“捕获”私有方法。

来自 Spring 参考:

由于 Spring 的 AOP 框架基于代理的性质,根据定义,受保护的方法不会被拦截,对于 JDK 代理(这不是适用)也不适用于 CGLIB 代理(这在技术上是可行的,但不推荐用于 AOP 目的)。因此,任何给定的切入点都将仅与 public 方法匹配! 如果您的拦截需要包括 protected/private 方法甚至构造函数,请考虑使用 Spring 驱动的原生 AspectJ 编织,而不是 Spring 基于代理的 AOP 框架。这就构成了不同的AOP使用模式,具有不同的特点,所以一定要先熟悉weaving再做决定。

所以你能做的最好的事情就是改变你的方法public--> public String testTimeTaken()