为什么-@Value-可以获取配置中心的值?

本文介绍了Spring如何通过@Value获取配置中心的值,详细讲解了配置中心的数据来源、实时发布更新配置的原理,并展示了自定义注解以支持动态更新配置的方法。文章通过代码示例解释了如何添加自定义配置属性源以及如何监听配置变化并进行更新。
摘要由CSDN通过智能技术生成

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ValueAnnotationDemo.class);

Map<String, Object> map = new HashMap<>();
map.put(“my.name”, “coder小黑”);
context.getEnvironment()
.getPropertySources()
.addFirst(new MapPropertySource(“coder-xiaohei-test”, map));
}
}

总结

  1. Spring 通过 PropertySource 来抽象配置属性源, PropertySource 允许有多个。MutablePropertySources
  2. 在 Spring 容器启动的时候,会默认加载 systemEnvironment 和 systemProperties。StandardEnvironment#customizePropertySources
  3. 我们可以通过 @PropertySource 注解或者 MutablePropertySources API 来添加自定义配置属性源
  4. Environment 是 Spring 对 profiles 和 properties 的抽象,默认实现是 StandardEnvironment
  5. @Value 的注入由 AutowiredAnnotationBeanPostProcessor 来提供支持,数据源来自于 PropertySource

public class Demo {

@Value(“${os.name}”) // 来自 system properties
private String osName;

@Value(“${user.name}”) // 通过 MutablePropertySources API 来注册
private String username;

@Value(“${os.version}”) // 测试先后顺序
private String osVersion;

public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(Demo.class);
ConfigurableEnvironment environment = context.getEnvironment();
MutablePropertySources propertySources =

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值