从0开始SpringBoot -4: 多环境配置

191 阅读2分钟

开发中必定会有多环境的配置场景

Spring 多配置 文档

  1. 外部化配置
    Spring Boot 允许你将配置外部化,以便在不同的环境中使用相同的应用程序代码。你可以使用属性文件、YAML 文件、环境变量和命令行参数来外部化配置。属性值可以通过 @Value 注解直接注入到你的 Bean 中,通过 Spring 的 Environment 抽象访问,或者通过 @ConfigurationProperties 绑定到结构化对象。

Spring Boot 使用一种非常特殊的 PropertySource 顺序,旨在允许合理地覆盖值。属性按以下顺序被考虑:

  1. Devtools 全局设置属性:位于主目录下的 Devtools 全局设置属性(当 Devtools 激活时,路径为 ~/.spring-boot-devtools.properties)。
  2. 测试中的 @TestPropertySource 注解:在测试类上使用的 @TestPropertySource 注解。
  3. 测试中的 properties 属性:在 @SpringBootTest 和用于测试应用程序特定部分的测试注解中使用的 properties 属性。
  4. 命令行参数:通过命令行传递的参数。
  5. SPRING_APPLICATION_JSON 中的属性:嵌入在环境变量或系统属性中的内联 JSON。
  6. ServletConfig 初始化参数:Servlet 配置的初始化参数。
  7. ServletContext 初始化参数:Servlet 上下文的初始化参数。
  8. JNDI 属性:来自 java:comp/env 的 JNDI 属性。
  9. Java 系统属性:通过 System.getProperties() 获取的系统属性。
  10. 操作系统环境变量:操作系统的环境变量。
  11. RandomValuePropertySource:仅在 random.* 中具有属性的随机值属性源。
  12. 打包的 jar 外部的特定配置文件属性(Profile-specific application properties):位于打包的 jar 外部的特定配置文件属性(如 application-{profile}.properties 和 YAML 变体)。
  13. 打包的 jar 内部的特定配置文件属性(Profile-specific application properties):位于打包的 jar 内部的特定配置文件属性(如 application-{profile}.properties 和 YAML 变体)。
  14. 打包的 jar 外部的应用程序属性:位于打包的 jar 外部的应用程序属性(如 application.properties 和 YAML 变体)。
  15. 打包的 jar 内部的应用程序属性:位于打包的 jar 内部的应用程序属性(如 application.properties 和 YAML 变体)。
  16. @Configuration 类上的 @PropertySource 注解:在配置类上使用的 @PropertySource 注解。
  17. 默认属性:通过 SpringApplication.setDefaultProperties 设置的默认属性。

Profile-specific application properties

这里我们常用到 12,13 提到的 Profile-specific application properties 来实现配置不同的环境变量,例如 在application.properties下,生成对应的 env.properties (yml配置文件同理)

image.png

指定默认激活的环境

# config multi profiles
spring.profiles.active=dev

profile 中的配置

## config spring datasource
spring.datasource.jdbcUrl=jdbc:mysql://127.0.0.1:3306/SpringBootDemo
spring.datasource.username=root
spring.datasource.password=jakexxxx
spring.datasource.maximum-pool-size=30

本地运行时可以配置多个application,在CLI arguments 中加入对应的配置来区分环境

// 这里拿dev举例,可以换test/online
--spring.profiles.active=dev

Screenshot 2025-02-11 at 16.03.45.png

Screenshot 2025-02-11 at 16.06.04.png

CLI 启动命令

/Library/Java/JavaVirtualMachines/jdk-22.jdk/Contents/Home/bin/java -。。。。。 com.example.DemoApplication --spring.profiles.active=dev