java - 添加Spring AOP后@Autowired返回null

标签 java spring spring-boot spring-aop

我有 Spring Boot 项目,工作得很好。但是当我添加 spring AOP 时,当我使用 @Autowired 变量时,它会导致空指针。

这是我的 AOP 代码。

    @Autowired
    private Service service;
    
    private final org.apache.commons.logging.Log log = LogFactory.getLog(this.getClass());
    
    @Around("execution(* com.kpi.ninja..*.*(..))")
    public Object logTimeMethod(ProceedingJoinPoint joinPoint) throws Throwable {
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();
            System.out.println("Entering in Method :  " + joinPoint.getSignature().getName());
            System.out.println("Class Name :  " + joinPoint.getSignature().getDeclaringTypeName());
            System.out.println("Target class : " + joinPoint.getTarget().getClass().getName());
            Object retVal = joinPoint.proceed();

            stopWatch.stop();
            
            
            StringBuffer logMessage = new StringBuffer();
            logMessage.append(joinPoint.getTarget().getClass().getName());
            logMessage.append(".");
            logMessage.append(joinPoint.getSignature().getName());
            logMessage.append("(");
            // append args
            Object[] args = joinPoint.getArgs();
            for (int i = 0; i < args.length; i++) {
                logMessage.append(args[i]).append(",");
            }
            if (args.length > 0) {
                logMessage.deleteCharAt(logMessage.length() - 1);
            }

            logMessage.append(")");
            logMessage.append(" execution time: ");
            logMessage.append(stopWatch.getTotalTimeMillis());
            logMessage.append(" ms");
            log.info(logMessage.toString());
            
            return retVal;
    }

Here is the image that shows the null pointer error where i used the autowired variable

最佳答案

您建议使用所有方法:@Around("execution(* com.kpi.ninja..*.*(..))")

所以我猜 Spring AOP 排除了您的 MyAspect 类以避免无限递归。

首先尝试将 @Around 切入点缩小到单个方法,看看它是否有效。

之后,使用切点注释将您的 logTimeMethod 排除在建议之外。

关于java - 添加Spring AOP后@Autowired返回null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50292685/

相关文章:

java - JPanel布局问题

java - MySQL并发读写一张表

java - spring - 同时使用简单的 SimpleUrlHandlerMapping 和 AnnotationMapping

spring - MaxUploadSizeExceededException 不调用 Spring 中的异常处理方法

spring-boot - 启动 zipkin 服务器时出错 : Prometheus requires that all meters with the same name have the same set of tag keys

java - spring-boot @ConditionalOnClass 是如何工作的?

Eclipse Spring Boot 构建路径包含重复条目

java - HashMap成员的并发修改

java - 检查AWS作业的状态

Spring Boot & ELB - 如何让负载均衡器将 http 重定向到 https?