工具類無法自動注入bean


@Component //把普通pojo實例化到spring容器中 0
public class MyUtil{
     // 這里是需要注入的Service
     @Autowired
     private MyService myService;
     private static MyUtil myUtil;
     /**
      * 沒有這個方法會報空指針,因為還沒注入完成就被注冊到speing容器中了 ,所以這里用一個局部變量保存注入內容,直接使用局部變量
      * 
      * 執行順序: construct>>PostConstruct>>static  所以在static中使用的對象都是在PostConstruct里提前組裝好的
      */
     @PostConstruct
     public void init() {      
          myUtil = this;
          myUtil.myService = this.myService;
      }
     
     public static void insertParam(int id){
          // 調用方法
          myUtil.myService.testInsert("xxx");
      }
}

 


免責聲明!

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



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