spring對象注入失敗問題

spring對象注入失敗

  • 問題描述

    筆者在編寫代碼中,希望構建一個工具類,在工具類中需要訪問dao層接口操作數據庫。於是便想在工具類中注入一個mabatis的mapper接口。

  • 代碼片段

public class LogUtil {

    @Autowired
    private LogMapper logMapper;

    public static final String INSERT = "insert";
    public static final String DELETE = "delete";
    public static final String UPDATE = "update";

    public int insertLog(String userName, String type, String content, String invoker){
        try{
            Log log = new Log(userName, type, content, invoker);
            log.preInsert();
            return logMapper.insert(log);
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }
}


// 方法調用
LogUtil logutil = new LogUtil();
logutil.insertLog("xx","xx","xx","xx");

於是產生了空指針異常,因爲LogMapper注入失敗。

  • 問題分析

    spring對象注入只有在已被spring容器管理的對象中進行,對象的依賴構成一個對象鏈。如對象A依賴對象B,對象B依賴對象C,則A在構建時先完成的B的構建,而B又依賴於C,於是只有C完成構建時,所有對象才能加載成功。而本例中,LogUtil並沒有被spring容器管理,所以也不會自動注入裏面的依賴項。

  • 解決方案

    將logutil也加入spring容器。

@Component
public class LogUtil {

    @Autowired
    LogMapper logMapper;

    public static final String INSERT = "insert";
    public static final String DELETE = "delete";
    public static final String UPDATE = "update";

    public int insertLog(String userName, String type, String content, String invoker){
        try{
            Log log = new Log(userName, type, content, invoker);
            log.preInsert();
            return logMapper.insert(log);
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }
}

加上@Component註解即可。

@Configuration
@Aspect
public class LogAspect {
    @Autowired
    LogUtil logUtil;

    Logger logger = (Logger) LoggerFactory.getLogger(LogAspect.class);
    ......
}

如果不想將對象讓spring容器管理,則可以自己獲取spring容器對象,然後獲取bean。
筆者使用時後臺使用springboot搭建,關於springboot怎麼獲取bean對象,請參見springboot獲取bean

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章