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));
}
}
总结
- Spring 通过
PropertySource
来抽象配置属性源,PropertySource
允许有多个。MutablePropertySources
- 在 Spring 容器启动的时候,会默认加载 systemEnvironment 和 systemProperties。
StandardEnvironment#customizePropertySources
- 我们可以通过
@PropertySource
注解或者MutablePropertySources API
来添加自定义配置属性源 Environment
是 Spring 对 profiles 和 properties 的抽象,默认实现是StandardEnvironment
@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 =