static類型autowired 注入失敗


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM