1. 程式人生 > >static類型autowired 註入失敗

static類型autowired 註入失敗

ostc .get 註入失敗 con 什麽 span 狀態 clas turn

原代碼:註入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); }

static類型autowired 註入失敗