1 配置文件

1.1 默认配置文件

默认配置文件:

  1. application.properties
  2. application.yml

1.2 多个配置文件

  1. application.properties
  2. application.yml
  3. application-dev.yml
  4. application-local.yml

根据配置决定哪个生效:spring.profiles.active=local

1.3 配置文件中属性读取

1.3.1 会取生效的配置文件找master前缀的配置

@ConfigurationProperties(prefix = “master”)

  1. @Component
  2. @Data
  3. @ConfigurationProperties(prefix = "master")
  4. public class MasterByDefaultProperties {
  5. private String name;
  6. private String sex;
  7. private String subject;
  8. }

1.3.2 会取生效的配置文件找“master.name”的配置

@Value(“${master.name}”)

  1. @Component
  2. @Data
  3. public class MasterByProperties {
  4. @Value("${master.name}")
  5. private String name;
  6. @Value("${master.sex}")
  7. private String sex;
  8. @Value("${master.subject}")
  9. private String subject;
  10. }

1.3.3 @PropertySource和@Value联合使用,取@PropertySource指定配置文件找对应的配置

  1. @Data
  2. @Component
  3. @PropertySource(value = "classpath:application.yml")
  4. public class MasterByDefaultYml {
  5. @Value("${master.name}")
  6. private String name;
  7. @Value("${master.sex}")
  8. private String sex;
  9. @Value("${master.subject}")
  10. private String subject;
  11. }

1.4 多个配置文件中相同属性的读取

读取方式跟上边一样,但是重名的属性,则根据优先级,优先级高的覆盖低的;

生效的主配置>生效的副配置 properties>yml

  1. # 生效的application-local.yml>application.properties
  2. 2019-06-11 16:43:16.414 INFO 5490 --- [main] com.wxx.modules.st.StApplication : The following profiles are active: local

2 配置方式优先级:

  1. a. 命令行参数
  2. b. 来自java:comp/envJNDI属性
  3. c. Java系统属性(System.getProperties())
  4. d. 操作系统环境变量
  5. e. RandomValuePropertySource配置的random.*属性值
  6. f. jar外部的application-{profile}.propertiesapplication.yml(带spring.profile)配置文件
  7. g. jar内部的application-{profile}.propertiesapplication.yml(带spring.profile)配置文件
  8. h. jar外部的application.propertiesapplication.yml(不带spring.profile)配置文件
  9. i. jar内部的application.propertiesapplication.yml(不带spring.profile)配置文件
  10. j. @Configuration注解类上的@PropertySource
  11. k. 通过SpringApplication.setDefaultProperties指定的默认属性