欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

springboot?靜態(tài)方法中使用@Autowired注入方式

 更新時(shí)間:2022年02月14日 10:55:53   作者:堯上有農(nóng)  
這篇文章主要介紹了springboot?靜態(tài)方法中使用@Autowired注入方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

靜態(tài)方法使用@Autowired注入

@Component
public class StructUtil {
    private static StructService structService;
    private static List<StructInfo> structInfos;
	
	// 通過重寫set注入
    @Autowired
    public void setStructService(StructService structService){
        StructUtil.structService = structService;
    }
    public static List<StructInfo> getStruct(){
        if(null==structInfos){
            structInfos = structService.getStruct();
        }
        return structInfos;
    }
}

靜態(tài)方法使用@Autowired注入的類

在寫公眾號(hào)開發(fā)的時(shí)候,有一個(gè)處理get請(qǐng)求,我想使用Spring提供的RestTemplate處理發(fā)送;

原來是這樣的

@Component
public ?class WeChatContant {
@Autowired
? ? private RestTemplate restTemplate;
?/**
? ? ?* 編寫Get請(qǐng)求的方法。但沒有參數(shù)傳遞的時(shí)候,可以使用Get請(qǐng)求
? ? ?*
? ? ?* @param url 需要請(qǐng)求的URL
? ? ?* @return 將請(qǐng)求URL后返回的數(shù)據(jù),轉(zhuǎn)為JSON格式,并return
? ? ?*/
? ? public ?JSONObject doGerStr(String url) throws IOException {
? ? ? ? ResponseEntity responseEntity = restTemplate.getForEntity
? ? ? ? ? ? ? ? (
? ? ? ? ? ? ? ? ? ? ? ? url,
? ? ? ? ? ? ? ? ? ? ? ? String.class
? ? ? ? ? ? ? ? );
? ? ? ? Object body = responseEntity.getBody();
? ? ? ? assert body != null;
? ? ? ? JSONObject jsonObject = JSONObject.fromObject(body);
? ? ? ? System.out.println(11);
? ? ? ? return jsonObject;
? ? }
}

但是到這里的話restTemplate這個(gè)值為空,最后導(dǎo)致空指針異常。發(fā)生的原因是

static模塊會(huì)被引入,當(dāng)class加載后。你的component組件的依賴還沒有初始化。

(你的依賴都是null)

解決方法

可以使用@PostConstruct這個(gè)注解解決

1,@PostConstruct 注解的方法在加載類的構(gòu)造函數(shù)之后執(zhí)行,也就是在加載了構(gòu)造函數(shù)之后,為此,可以使用@PostConstruct注解一個(gè)方法來完成初始化,@PostConstruct注解的方法將會(huì)在依賴注入完成后被自動(dòng)調(diào)用。

2,執(zhí)行優(yōu)先級(jí)高于非靜態(tài)的初始化塊,它會(huì)在類初始化(類加載的初始化階段)的時(shí)候執(zhí)行一次,執(zhí)行完成便銷毀,它僅能初始化類變量,即static修飾的數(shù)據(jù)成員。

自己理解的意思就是在component組件都加載完之后再加載

修改過后的代碼如下

@Component
public ?class WeChatContant {
?? ?@Autowired
? ? private RestTemplate restTemplate;
? ? private static RestTemplate restTemplateemp;
? ? @PostConstruct
? ? public void init(){
? ? ? ? restTemplateemp ?= restTemplate;
? ? }
? ? /**
? ? ?* 編寫Get請(qǐng)求的方法。但沒有參數(shù)傳遞的時(shí)候,可以使用Get請(qǐng)求
? ? ?*
? ? ?* @param url 需要請(qǐng)求的URL
? ? ?* @return 將請(qǐng)求URL后返回的數(shù)據(jù),轉(zhuǎn)為JSON格式,并return
? ? ?*/
? ? public static JSONObject doGerStr(String url) throws IOException {
? ? ? ? ResponseEntity responseEntity = restTemplateemp.getForEntity
? ? ? ? ? ? ? ? (
? ? ? ? ? ? ? ? ? ? ? ? url,
? ? ? ? ? ? ? ? ? ? ? ? String.class
? ? ? ? ? ? ? ? );
? ? ? ? Object body = responseEntity.getBody();
? ? ? ? assert body != null;
? ? ? ? JSONObject jsonObject = JSONObject.fromObject(body);
? ? ? ? System.out.println(11);
? ? ? ? return jsonObject;
? ? }
}

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論