Spring Boot 启动(二) 配置详解

Spring Boot 启动(二) 配置详解

Spring 系列目录(https://www.cnblogs.com/binarylei/p/10198698.html)

  1. Spring Boot 配置文件加载顺序
  2. Spring Boot 配置文件加载分析 - ConfigFileApplicationListener

一、Spring Framework 配置

略...

二、Spring Boot 配置

2.1 随机数配置

name.value=${random.int}
name.int=${random.int}
name.long=${random.long}
name.uuid=${random.uuid}
name.test1=${random.int(10)}
name.test2=${random.int[10,20]}

2.2 命令参数

java -jar xxx.jar --server.port=8080

2.3 多配置文件

applicaiton-dev.properties      # 开发环境
applicaiton-test.properties     # 测试环境
applicaiton-prod.properties     # 生产环境

配置文件关联 profile 除了以上方式,还有另外两种方式:

  • applicaiton-dev.properties 文件名指定剖面
  • applicaiton.properties && spring.profile=dev 文件内容配置 spring.profile
  • applicaiton-dev.properties && spring.profile=dev 文件名指定剖面且文件内容配置 spring.profile

2.4 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}.properties 或是 YAML 定义的配置文件。
  8. 位于当前应用 jar 包之内,针对不同 {profi1e} 环境的配置文件内容,例如 application-{profile}.properties 或是 YAM 定义的配置文件。
  9. 位于当前应用 jar 包之外的 application.properties 和 YAML 配置内容。
  10. 位于当前应用 jar 包之内的 application.properties 和 YAML 配置内容。
  11. 在 @Configuration 注解修改的类中,通过 @PropertySource 注解定义的属性。
  12. 应用默认属性,使用 SpringApplication.setDefaultProperties 定义的内容。

以上配置属性加载类如下:

  1. 第一项是在 prepareEnvironment -> configureEnvironment -> configurePropertySources 定义的 CommandLinePropertySource。
  2. 第二项是在 spring.factories 中定义的 SpringApplicationJsonEnvironmentPostProcessor 处理,也实现了 EnvironmentPostProcessor 接口,优先级高于 ConfigFileApplicationListener。
  3. 第三-五项是 Spring Framework 标准的属性,初始化 Environment 时配置。
  4. 第六项是在 ConfigFileApplicationListener 中定义的 RandomValuePropertySource。
  5. 第七-十项是在 ConfigFileApplicationListener 中加载配置文件,也实现了 EnvironmentPostProcessor 接口。

每天用心记录一点点。内容也许不重要,但习惯很重要!

猜你喜欢

转载自www.cnblogs.com/binarylei/p/10645232.html