开发中必定会有多环境的配置场景
- 外部化配置
Spring Boot 允许你将配置外部化,以便在不同的环境中使用相同的应用程序代码。你可以使用属性文件、YAML 文件、环境变量和命令行参数来外部化配置。属性值可以通过@Value注解直接注入到你的 Bean 中,通过 Spring 的Environment抽象访问,或者通过@ConfigurationProperties绑定到结构化对象。
Spring Boot 使用一种非常特殊的 PropertySource 顺序,旨在允许合理地覆盖值。属性按以下顺序被考虑:
- Devtools 全局设置属性:位于主目录下的 Devtools 全局设置属性(当 Devtools 激活时,路径为
~/.spring-boot-devtools.properties)。 - 测试中的
@TestPropertySource注解:在测试类上使用的@TestPropertySource注解。 - 测试中的
properties属性:在@SpringBootTest和用于测试应用程序特定部分的测试注解中使用的properties属性。 - 命令行参数:通过命令行传递的参数。
SPRING_APPLICATION_JSON中的属性:嵌入在环境变量或系统属性中的内联 JSON。ServletConfig初始化参数:Servlet 配置的初始化参数。ServletContext初始化参数:Servlet 上下文的初始化参数。- JNDI 属性:来自
java:comp/env的 JNDI 属性。 - Java 系统属性:通过
System.getProperties()获取的系统属性。 - 操作系统环境变量:操作系统的环境变量。
RandomValuePropertySource:仅在random.*中具有属性的随机值属性源。- 打包的 jar 外部的特定配置文件属性(Profile-specific application properties):位于打包的 jar 外部的特定配置文件属性(如
application-{profile}.properties和 YAML 变体)。 - 打包的 jar 内部的特定配置文件属性(Profile-specific application properties):位于打包的 jar 内部的特定配置文件属性(如
application-{profile}.properties和 YAML 变体)。 - 打包的 jar 外部的应用程序属性:位于打包的 jar 外部的应用程序属性(如
application.properties和 YAML 变体)。 - 打包的 jar 内部的应用程序属性:位于打包的 jar 内部的应用程序属性(如
application.properties和 YAML 变体)。 @Configuration类上的@PropertySource注解:在配置类上使用的@PropertySource注解。- 默认属性:通过
SpringApplication.setDefaultProperties设置的默认属性。
Profile-specific application properties
这里我们常用到 12,13 提到的 Profile-specific application properties 来实现配置不同的环境变量,例如 在application.properties下,生成对应的 env.properties (yml配置文件同理)
指定默认激活的环境
# 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
CLI 启动命令
/Library/Java/JavaVirtualMachines/jdk-22.jdk/Contents/Home/bin/java -。。。。。 com.example.DemoApplication --spring.profiles.active=dev