@RefreshScope引起的取值為null

網(wǎng)上找了一堆介紹,越說越糊涂,后面自己測(cè)試后明白了.

先上代碼

  • 注入配置值方法1: @value
@RefreshScope
@Configuration
public class ScopeTestConfig {

    @Value("config.test.one")
    public String one;

    @Value("config.test.two")
    private String two;

    public String getOne() {
        return one;
    }

    public String getTwo() {
        return two;
    }
}
  • 注入配置值方法2: @ConfigurationProperties(prefix = "config.test")
@RefreshScope
@Configuration
@ConfigurationProperties(prefix = "config.test")
public class ScopeTestConfig1 {

    public String one;

    private String two;

    public String getOne() {
        return one;
    }

    public String getTwo() {
        return two;
    }

}
  • 取值方式1: 通過注入bean的field獲取值
    @Autowired
    ScopeTestConfig config;

    void test(){
        String fieldVal1 = config.one;
    }

  • 取值方式2: 通過注入bean的方法間接讀取field獲取值
    @Autowired
    ScopeTestConfig config;

    void test(){
        String getMethod1 = config.getOne();
        String getMethod2 = config.getTwo();
    }

  • 取值清單(2種方式情況一樣)

取值方式 無@RefreshScope 有@RefreshScope
方式1(field取值) 有值 null
方式2(方法取值) 有值 有值
  • 總結(jié)陳詞

@RefreshScope 會(huì)使注入的值放到代理類中,
而當(dāng)前bean的屬性字段是沒有值的,直接讀取bean的field會(huì)為null,
只有通過方法(不一定是get方法)才會(huì)觸發(fā)去代理類中取值.

很多遇到在@Controller中直接@Value獲取不到值,解決方法是定義另外一個(gè)配置類,再取值就可以了,其實(shí)忽略了取值的方式, 都是代理惹的禍.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容