如何在靜態方法中使用注入的對象

1:在通常情況下,如果需要在靜態方法中使用注入的對象,注入的對象會爲null。

 例如:

public Class utils{

@Autowired
public  TenantInfoDao tenantInfoDao;

   public static void test(String id){

     String mac = tenantInfoDao.getMac(id);

}

}

此時會報空指針異常。因爲 靜態方法屬於類,而屬性對象屬於對象實例。靜態方法比實例方法初始化快,所以tenantInfoDao還沒實例化就被使用,報空。

2 解決方案:

public Class utils{

@Autowired
public  TenantInfoDao tenantInfoDao;
private static utils util;
@PostConstruct
public void init(){
    util=this;
    util.tenantInfoDao = this.tenantInfoDao;
}

   public static void test(String id){

   //使用時注意

     String mac = util.tenantInfoDao.getMac(id);

}

}

@PostConstruct在構造函數之後執行,init()方法之前執行。

3 當然,最簡單的方法是:直接new 一個TenantInfoDao (),這樣可能有點不優雅。這時可以考慮使用單例模式,獲取唯一實例TenantInfoDao 。

單例工具類(網上有很多):

 public  Class singleUtil{

   private static  volatile TenantInfoDao tenantInfoDao;

 private singleUtil(){}

public static TenantInfoDao getInstance() {
        if (tenantInfoDao== null) {
            synchronized (singleUtil.class) {
                if (tenantInfoDao== null) {
                    tenantInfoDao= new TenantInfoDao();
                }
            }
        }
        return tenantInfoDao;
    }

 

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章