美文网首页
@RefreshScope引起的取值为null

@RefreshScope引起的取值为null

作者: 伊夫_艾尔斯 | 来源:发表于2022-12-29 18:12 被阅读0次

网上找了一堆介绍,越说越糊涂,后面自己测试后明白了.

先上代码

  • 注入配置值方法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(方法取值) 有值 有值
  • 总结陈词

@RefreshScope 会使注入的值放到代理类中,
而当前bean的属性字段是没有值的,直接读取bean的field会为null,
只有通过方法(不一定是get方法)才会触发去代理类中取值.

很多遇到在@Controller中直接@Value获取不到值,解决方法是定义另外一个配置类,再取值就可以了,其实忽略了取值的方式, 都是代理惹的祸.

相关文章

网友评论

      本文标题:@RefreshScope引起的取值为null

      本文链接:https://www.haomeiwen.com/subject/krbtcdtx.html