繁体   English   中英

在添加Spring AOP之后@Autowire返回null

[英]@Autowire return null after adding Spring AOP

我有spring boot项目,它工作得很好。 但是当我添加spring AOP时,当我使用@Autowired变量时,它会导致我成为nullpointer。

这是我的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 {
    //HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
    System.out.println("***********************************************");

        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());

        System.out.println("***********************************************");

        return retVal;
}

这是显示空指针错误的图像,其中我使用了自动装配变量

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

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

尽量缩小范围@Around poincut到一个单一的方法先来看看它是否工作。

之后,使用logTimeMethod注释从建议中排除logTimeMethod

您正在使用nullpointer,因为spring无法初始化Service类,您需要在spring上下文xml中添加服务,因此声明一个新bean:

<bean id="service" class="[package].Service"></bean>

如果没有上下文,则应创建一个上下文,并在类声明中添加批注以设置context.xml的路径位置:

   @ContextConfiguration(locations = { "classpath:/context.xml" })
   public class YourClass{
       @Autowired
       Service service

      ...methods
   }

请确保使用@Autowired的类已用@ Component / @ Service / @ Bean注释。您发布的代码不包含初始类定义或spring XML,因此不确定您是否已添加是否添加注释。

@Component or @Controller or @Bean or @Service/@Repository 
Class ACB{

@Autowired
private Service service;

.....

}

通过将一个bean的实例放置到另一个bean的实例的所需字段中来进行自动装配。 这两个类都应为bean,即应将它们定义为存在于应用程序上下文中。

暂无
暂无

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

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