在靜態工具類中註入Service的解決方案
阿新 • • 發佈:2018-08-06
空指針異常 靜態屬性 autowire code javascrip ans 當前 muse tco
由於工具類中方法一般都是靜態的,所以要求該屬性也要是靜態的(Service)。
但是由於Spring/SpringBoot正常情況下不能支持註入靜態屬性(會報空指針異常)。
主要原因在於:Spring的依賴註入實際上是依賴於Set方法進行註入值的,Spring是基於對象層面的依賴註入,而靜態屬性/靜態變量實際上是屬於類的。
解決方案一:
給當前的工具類加上@Component,使其成為一個bean對象
聲明一個靜態的屬性(加上註解@Autowired),一個非靜態的屬性。
聲明一個返回值為void並且不能拋出異常的方法,在其中將非靜態屬性賦值給靜態屬性。該方法上加上註解@PostConstruct
這樣就將service的值註入了進來。示例代碼如下:
@Component public class BaseUtil { @Autowired private ISystemOrganService systemOrganServiceTemp; @Autowired private ISystemUserService systemUserServiceTemp; private static ISystemOrganService systemOrganService; private static ISystemUserService systemUserService; @PostConstruct public void init(){ systemOrganService = systemOrganServiceTemp; systemUserService = systemUserServiceTemp; }
在靜態工具類中註入Service的解決方案