簡體   English   中英

@Autowired bean 在靜態方法中為 null

[英]@Autowired bean is coming as null at static method

我有兩個類名,Bean 類和 Util 類。 在 Util 類中,我想從 Bean 類中調用該方法。 但問題是當我在 Util 類中@Autowired Bean 類時。 由於 Util 類中的靜態方法,存在空指針異常。 這是我的代碼。

public class Util{

@Autowired
private static BaseServiceCommonPropertiesBean baseServiceCommonPropertiesBean;

private static String PASSPHRASE = baseServiceCommonPropertiesBean.getBassURL();
System.out.print(PASSPHRASE);

}

這是 BaseServiceCommonPropertiesBean 類

public class BaseServiceCommonPropertiesBean {

@Value("#{baseServiceapplicationProperties['mobi.sc.travellers.amr.email.base.url']}")
    private String baseUrl;

public String getBaseUrl(){
        return baseUrl;
    }

}

每當系統讀取 baseServiceCommonPropertiesBean.getPassPhrase() 方法時。 它熄滅並停止工作。 在它不起作用之前,我嘗試了@Postconstruct 注釋。 謝謝。

您不能@Autowired 靜態字段,從 BaseServiceCommonPropertiesBean 中刪除靜態字段或將您的 Util 重寫為如下所示:

@Component
public class Util{

private static BaseServiceCommonPropertiesBean baseServiceCommonPropertiesBean;

@Autowired
    public void setBaseServiceCommonPropertiesBean(BaseServiceCommonPropertiesBean baseServiceCommonPropertiesBean){
        Util.baseServiceCommonPropertiesBean = baseServiceCommonPropertiesBean;
    }

private static String PASSPHRASE = baseServiceCommonPropertiesBean.getBassURL();
System.out.print(PASSPHRASE);

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM