03.SpringBoot 之配置文件加载顺序

1. profile

代码已经上传至 https://github.com/masteryourself-tutorial/tutorial-spring ,详见 tutorial-spring-boot-core/tutorial-spring-boot-profile 工程

1.1 多 profile 环境

  • 在编写配置文件时,文件名可以是 application-{profile}.properties/yml

  • 默认使用 application.properties 的配置

1.2 多 profile 示例

1. application.properties
server.port=8080
## 激活 uat 环境, 如果不激活默认使用 8080
# spring.profiles.active=uat
2. application.yml
  • yml 支持多文档块方式,即以 --- 来区分
## 指定属于 uat 环境
spring:
  profiles: uat
server:
  port: 8083

---

## 指定属于 prod 环境
spring:
  profiles: prod
server:
  port: 8084
3. application-dev.properties
server.port=8081
4. application-test.yml
server:
  port: 8081

1.3 激活 profile

1.3.1 配置文件
  • 在配置文件中指定 spring.profiles.active=uat 激活 uat 环境
1.3.2 命令行参数
  • 如果是打成 jar 包,则加上 --spring.profiles.active=uat
java -jar study-spring-boot-profile-1.0.0-SNAPSHOT.jar --spring.profiles.active=uat
  • 如果是在 IDEA 中,则在 Program arguments 中添加配置
1.3.3 虚拟机参数
  • 如果是打成 jar 包,则加上 -Dspring.profiles.active=uat, 注意和命令行参数的位置不同
java -jar -Dspring.profiles.active=uat  study-spring-boot-profile-1.0.0-SNAPSHOT.jar
  • 如果是在 IDEA 中,则在 VM options 中添加配置
1.3.4 单元测试
  • 可以使用 @ActiveProfiles 来激活某个环境
@RunWith(SpringRunner.class)
@ActiveProfiles({"dev", "test"})
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class ProfileApplicationTest {

2. 配置文件加载位置

  • springboot 启动会扫描以下位置的 application.properties 或者 application.yml 文件作为 Spring boot 的默认配置文件,优先级由高到底,高优先级的配置会覆盖低优先级的配置
file:./config/ :即当前路径下的 config 目录

file:./ :即当前项目路径

classpath:/config/ :即类路径文件下的 config 目录

classpath:/ :即类路径的根目录,这也是 `application.properties` 文件的默认位置
  • 可以通过 --spring.config.location=D:/application.properties 来改变默认的配置文件位置

3. 外部配置加载顺序

  • SpringBoot 也可以从以下位置加载配置; 优先级从高到低; 高优先级的配置覆盖低优先级的配置,所有的配置会形成互补配置
1. 命令行参数
2. 来自 java:comp/env 的 JNDI 属性
3. Java系统属性(System.getProperties())
4. 操作系统环境变量
5. RandomValuePropertySource 配置的 random.* 属性值
6. jar 包外部的 application-{profile}.properties 或 application.yml (带 spring.profile) 配置文件
7. jar 包内部的 application-{profile}.properties 或 application.yml (带 spring.profile) 配置文件
8. jar 包外部的 application.properties 或 application.yml (不带 spring.profile) 配置文件
9. jar 包内部的 application.properties 或 application.yml (不带 spring.profile) 配置文件
10. @Configuration 注解类上的 @PropertySource
11. 通过 SpringApplication.setDefaultProperties 指定的默认属性
发布了37 篇原创文章 · 获赞 3 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/masteryourself/article/details/105016454