原代碼:注入commonService對象失敗
@Autowired private static CommonService commonService;
public static List<Map<String, Object>> getCode(String codeType, boolean allOption ,String orderType){ return commonUtil.commonService.getCode(codeType, allOption, orderType); }
commonService在static狀態下不能夠被依賴注入,會拋出運行時異常java.lang.NullPointerException,為什么呢?
靜態變量/類變量不是對象的屬性,而是一個類的屬性,spring則是基於對象層面上的依賴注入.
解決方式1:
@Autowired private CommonService commonService; private static CommonUtil commonUtil; @PostConstruct public void init() { commonUtil = this; commonUtil.commonService = this.commonService; } public static List<Map<String, Object>> getCode(String codeType, boolean allOption ,String orderType){ return commonUtil.commonService.getCode(codeType, allOption, orderType); }