springboot 如何解決static調(diào)用service為null
@PostConstruct注解好多人以為是Spring提供的。其實(shí)是Java自己的注解。
Java中該注解的說明:@PostConstruct該注解被用來修飾一個(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. JavaScript實(shí)現(xiàn)多球運(yùn)動(dòng)效果2. 存儲(chǔ)于xml中需要的HTML轉(zhuǎn)義代碼3. 匹配模式 - XSL教程 - 44. ASP中if語句、select 、while循環(huán)的使用方法5. CSS Hack大全-教你如何區(qū)分出IE6-IE10、FireFox、Chrome、Opera6. SpringMVC+Jquery實(shí)現(xiàn)Ajax功能7. XML入門精解之結(jié)構(gòu)與語法8. ASP.NET MVC使用異步Action的方法9. layui Ajax請(qǐng)求給下拉框賦值的實(shí)例10. JS中map和parseInt的用法詳解
