yaml

  1. # 参数之间的引用
  2. book:
  3. name: SpringCloud
  4. author: ZhaiYongchao
  5. desc: ${book.author} is writing ${book.name}》
  6. # 使用随机数
  7. randomValue:
  8. stringValue: ${random.value}
  9. longValue: ${random.long}
  10. intValue1: ${random.int}
  11. intValue2: ${random.int(10)}
  12. intValue3: ${random.int[10,20]}
  13. # 多环境配置
  14. spring:
  15. profiles:
  16. active: dev/test/prod
  17. # list类型
  18. spring:
  19. my-example:
  20. url:
  21. - http://example.com
  22. - http://spring.io
  23. url1: http://example.com, http://spring.io
  24. # Map类型
  25. spring:
  26. my-example:
  27. foo: bar
  28. hello: world
  29. # 如果Map类型的key包含非字母数据和 - 的字符,需要用[]
  30. '[foo.baz]': bar

Spring Boot 对数据文件的加载机制

  1. 命令行传入的参数
  2. SPRING_APPLICATION_JSON中的属性。SPRING_APPLICATION_JSON是以JSON格式配置在环境变量中的内容
  3. java:comp/env 中的 JNDI 属性
  4. Java的系统属性,可以通过 System.getProperties() 获得的内容
  5. 操作系统的环境变量
  6. 通过 random.* 配置的随机属性
  7. 位于当前应用jar包之外,针对不同 {profile} 环境的配置文件内容,如:application-{profile}.yaml定义的配置文件
  8. 位于当前应用jar包之内,针对不同 {profile} 环境的配置文件内容,如:application-{profile}.yaml定义的配置文件
  9. 位于当前应用jar包之外的 application.yaml定义的配置文件
  10. 位于当前应用jar包之内的 application.yaml定义的配置文件
  11. 在 @Configuration 注解修改的类中,通过 @PropertySource 注解定义的属性
  12. 应用默认属性,使用 SpringApplication.setDefaultProperties 定义的内容

    读取配置文件中的内容

    @Value(“${}”)

    this.environment.containsProperty(“”)

    绑定API

    简单类型:

    1. @ConfigurationProperties(prefix = "com.didispace")
    2. public class FooProperties {
    3. private String foo;
    4. }
    1. @SpringBootApplication
    2. public class Application {
    3. public static void main(String[] args) {
    4. ApplicationContext context = SpringApplication.run(Application.class, args);
    5. Binder binder = Binder.get(context.getEnvironment());
    6. // 绑定简单配置
    7. FooProperties foo = binder.bind("com.didispace", Bindable.of(FooProperties.class)).get();
    8. System.out.println(foo.getFoo());
    9. }
    10. }

    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!

  1. ```java
  2. ApplicationContext context = SpringApplication.run(Application.class, args);
  3. Binder binder = Binder.get(context.getEnvironment());
  4. // 绑定List配置
  5. List<String> post = binder.bind("com.didispace.post", Bindable.listOf(String.class)).get();
  6. System.out.println(post);
  7. List<PostInfo> posts = binder.bind("com.didispace.posts", Bindable.listOf(PostInfo.class)).get();
  8. System.out.println(posts);