@RefreshScope引起的取值为null

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

先上代码

  • 注入配置值方法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获取不到值,解决方法是定义另外一个配置类,再取值就可以了,其实忽略了取值的方式, 都是代理惹的祸.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容