springboot 如何解決static調(diào)用service為null
@PostConstruct注解好多人以為是Spring提供的。其實(shí)是Java自己的注解。
Java中該注解的說(shuō)明:@PostConstruct該注解被用來(lái)修飾一個(gè)非靜態(tài)的void()方法。被@PostConstruct修飾的方法會(huì)在服務(wù)器加載Servlet的時(shí)候運(yùn)行,并且只會(huì)被服務(wù)器執(zhí)行一次。PostConstruct在構(gòu)造函數(shù)之后執(zhí)行,init()方法之前執(zhí)行。
通常我們會(huì)是在Spring框架中使用到@PostConstruct注解 該注解的方法在整個(gè)Bean初始化中的執(zhí)行順序:
Constructor(構(gòu)造方法) -> @Autowired(依賴注入) -> @PostConstruct(注釋的方法)
實(shí)戰(zhàn):
在靜態(tài)方法中調(diào)用依賴注入的Bean中的方法。
@Componentpublic class LeaveCode { @Autowired private IPlaLeaveApplyService plaLeaveApplyService; public static LeaveCode leaveCode; /** * 解決 static方法調(diào)用 注入的service為null */ @PostConstruct public void init(){leaveCode = this;leaveCode.plaLeaveApplyService = this.plaLeaveApplyService; } }SpringBoot 靜態(tài)類引入service 空指針/NULL
Spring注入service后,正常情況下非靜態(tài)方法是可以正常使用注冊(cè)的service的,當(dāng)時(shí)用靜態(tài)類引用的時(shí)候,靜態(tài)類static方法會(huì)將spring注入的service清空。
造成引用空指針的情況,如何解決呢?@Componentpublic class UserUtils { @Autowired private UserService userService; private static UserUtils userUtils; @PostConstruct public void init() {userUtils = this;userUtils.userService = this.userService; }}
使用:
User user = userUtils.userService.getUser(loginCode);
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. python爬蟲實(shí)戰(zhàn)之制作屬于自己的一個(gè)IP代理模塊2. asp批量添加修改刪除操作示例代碼3. 基于javaweb+jsp實(shí)現(xiàn)企業(yè)財(cái)務(wù)記賬管理系統(tǒng)4. css代碼優(yōu)化的12個(gè)技巧5. 如何在jsp界面中插入圖片6. Vue element ui用戶展示頁(yè)面的實(shí)例7. Ajax返回值類型與用法實(shí)例分析8. 使用FormData進(jìn)行Ajax請(qǐng)求上傳文件的實(shí)例代碼9. .NET6打包部署到Windows Service的全過(guò)程10. HTML 絕對(duì)路徑與相對(duì)路徑概念詳細(xì)
