Spring AOP切面类依赖注入失败问题解决

2022-08-12 14:07:36

最近在项目中使用到了Spring AOP结合AspectJ注解为项目增加系统操作日志记录功能,遇到的问题是在切面类中使用注解的方式注入Service对象失败,导致日志记录功能无法使用。报如下空指针异常:


第一行是日志切面类中的方法,第二行是Controller中的方法。
我觉得应该是spring加载配置文件时是有顺序引起的,但是不知道是什么顺序。。

待解决,至今没找到解决方法。。。

update 2017-5-25 22:11:43

目前的解决办法是通过实现一个ApplicationContext工具类进行手动注入,不知道还有没有更好的办法。

package com.june.util;
 
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
 
@Component
public class ApplicationContextUtils implements ApplicationContextAware {
     
    private static ApplicationContext applicationContext;
 
    private ApplicationContextUtils(){}
     
    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        applicationContext = context;
    }
     
    public static <T> T getBean(Class<T> beanClass) {
        return applicationContext.getBean(beanClass);
    }
     
    public static <T> T getBean(String beanName, Class<T> beanClass) {
        return applicationContext.getBean(beanName, beanClass);
    }
 
}

在切面类中使用:

@Aspect
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class SysOperateLogAspect {
     
    private SysOperateLogService sysOperateLogService;
     
    public SysOperateLogAspect() {
        this.sysOperateLogService = ApplicationContextUtils.getBean(SysOperateLogService.class);
    }
}

希望能找到更好的办法。

  • 作者:ChengJune
  • 原文链接:https://blog.csdn.net/xjc_csdn/article/details/74533749
    更新时间:2022-08-12 14:07:36