yaml
# 参数之间的引用book:name: SpringCloudauthor: ZhaiYongchaodesc: ${book.author} is writing 《${book.name}》# 使用随机数randomValue:stringValue: ${random.value}longValue: ${random.long}intValue1: ${random.int}intValue2: ${random.int(10)}intValue3: ${random.int[10,20]}# 多环境配置spring:profiles:active: dev/test/prod# list类型spring:my-example:url:- http://example.com- http://spring.iourl1: http://example.com, http://spring.io# Map类型spring:my-example:foo: barhello: world# 如果Map类型的key包含非字母数据和 - 的字符,需要用[]'[foo.baz]': bar
Spring Boot 对数据文件的加载机制
- 命令行传入的参数
- SPRING_APPLICATION_JSON中的属性。SPRING_APPLICATION_JSON是以JSON格式配置在环境变量中的内容
- java:comp/env 中的 JNDI 属性
- Java的系统属性,可以通过 System.getProperties() 获得的内容
- 操作系统的环境变量
- 通过 random.* 配置的随机属性
- 位于当前应用jar包之外,针对不同 {profile} 环境的配置文件内容,如:application-{profile}.yaml定义的配置文件
- 位于当前应用jar包之内,针对不同 {profile} 环境的配置文件内容,如:application-{profile}.yaml定义的配置文件
- 位于当前应用jar包之外的 application.yaml定义的配置文件
- 位于当前应用jar包之内的 application.yaml定义的配置文件
- 在 @Configuration 注解修改的类中,通过 @PropertySource 注解定义的属性
应用默认属性,使用 SpringApplication.setDefaultProperties 定义的内容
读取配置文件中的内容
@Value(“${}”)
this.environment.containsProperty(“”)
绑定API
简单类型:
@ConfigurationProperties(prefix = "com.didispace")public class FooProperties {private String foo;}
@SpringBootApplicationpublic class Application {public static void main(String[] args) {ApplicationContext context = SpringApplication.run(Application.class, args);Binder binder = Binder.get(context.getEnvironment());// 绑定简单配置FooProperties foo = binder.bind("com.didispace", Bindable.of(FooProperties.class)).get();System.out.println(foo.getFoo());}}
list类型: ```yaml com.didispace.post[0]=Why Spring Boot com.didispace.post[1]=Why Spring Cloud
com.didispace.posts[0].title=Why Spring Boot com.didispace.posts[0].content=It is perfect! com.didispace.posts[1].title=Why Spring Cloud com.didispace.posts[1].content=It is perfect too!
```javaApplicationContext context = SpringApplication.run(Application.class, args);Binder binder = Binder.get(context.getEnvironment());// 绑定List配置List<String> post = binder.bind("com.didispace.post", Bindable.listOf(String.class)).get();System.out.println(post);List<PostInfo> posts = binder.bind("com.didispace.posts", Bindable.listOf(PostInfo.class)).get();System.out.println(posts);
