1. 程式人生 > >Spring AOP切面類依賴注入失敗問題解決

Spring AOP切面類依賴注入失敗問題解決

最近在專案中使用到了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);
    }
}

希望能找到更好的辦法。

相關推薦

no