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

来源:互联网 发布:奥尼尔nba数据 编辑:程序博客网 时间:2024/05/17 02:22

最近在项目中使用到了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; @Componentpublic 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);    }}

希望能找到更好的办法。

原创粉丝点击