@Autowired注入service為null的問題及解決方案
@Autowired注入service為null
今天在一個普通類中注入service時出現(xiàn)了一個問題,我用@Autowired注入的service為null。
最終我是通過以下方案解決
1.在類上標注該類為組件也就是@Component
2.靜態(tài)初始化當前類
3.在初始化service的方法上加上注解@PostConstruct,這樣方法就會在Bean初始化之后被Spring容器執(zhí)行
4.調(diào)用時通過類來調(diào)用
@Component
public class LogUtil {
@Autowired
private LogService logService;
private static LogUtil logUtil; // 靜態(tài)初使化當前類
public static void saveLog(String userName, String result) {
Log log = new Log(userName+"", result);
try {
logUtil.logService.add(log);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@PostConstruct
public void init() {
logUtil = this;
logUtil.logService = this.logService;
}
}總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Lombok注解之@SuperBuilder--解決無法builder父類屬性問題
這篇文章主要介紹了Lombok注解之@SuperBuilder--解決無法builder父類屬性問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09
SpringBoot生成License的實現(xiàn)示例
License指的是版權(quán)許可證,那么對于SpringBoot項目,如何增加License呢?本文就來介紹一下,感興趣的可以了解一下2021-06-06
mybatis-plus如何根據(jù)任意字段saveOrUpdateBatch
MyBatisPlus saveOrUpdateBatch默認按主鍵判斷操作類型,若需按其他唯一字段(如agentId、period、type組合)判斷,需在service層重寫方法,通過predicate定義插入條件并結(jié)合consumer執(zhí)行更新邏輯,適用于批量和單條數(shù)據(jù)操作場景2025-09-09
spring boot activiti工作流的搭建與簡單使用
這篇文章主要給大家介紹了關(guān)于spring boot activiti工作流的搭建與簡單使用的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2018-08-08

