static 和 @postconstruct區別

摘自:  stackoverflow

static blocks are invoked when the class is being initialized, after it is loaded. The dependencies of your component haven't been initialized yet. That is why you get a NullPointerException (Your dependencies are null) .

Move your code to a method annotated with @PostConstruct. This will ensure that your code will run when all the dependencies of your component are initialized

翻譯:static模塊會被引入,當class加載後。你的component組件的依賴還沒有初始化。這就是爲什麼你的代碼塊會報空指針異常。(你的依賴都是null)

把你的代碼移到一個@PostConstruct聲明的方法塊中,這樣可以確保你的代碼執行在所有組件都加載以後。

發佈了17 篇原創文章 · 獲贊 2 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章