Spring Boot 配置源详解(完整版)


Spring Boot 配置源详解(完整版)

在这里插入图片描述


一、配置源加载顺序与优先级
配置源类型优先级顺序(从高到低)对应配置类/接口是否可覆盖典型文件/来源
命令行参数--key=value1(最高)SimpleCommandLinePropertySourceorg.springframework.core.env启动参数(如 java -jar app.jar --server.port=9090
SPRING_APPLICATION_JSON2MapPropertySourceorg.springframework.core.env环境变量或系统属性(如 -Dspring.application.json={...}
系统环境变量3SystemEnvironmentPropertySourceorg.springframework.core.env操作系统环境变量(如 export APP_NAME=myapp
@PropertySource 注解4PropertySourcesPropertyResolverorg.springframework.core.env代码中指定的资源路径(如 classpath:custom.properties
ServletConfig 初始化参数5ServletConfigPropertySourceorg.springframework.boot.envWeb 容器配置(如 Tomcat 的 context-param
ServletContext 初始化参数6ServletContextPropertySourceorg.springframework.boot.envWeb 容器配置(如 Tomcat 的 init-param
JNDI 环境变量7JndiPropertySourceorg.springframework.core.envJNDI 服务器配置(如 java:comp/env
随机属性random.*8RandomValuePropertySourceorg.springframework.boot.env自动生成随机值(如 random.number=12345
类路径 application.properties/.yml9YamlPropertySourceLoader, PropertiesPropertySourceLoaderorg.springframework.boot.envsrc/main/resources/application.properties
资源目录 application.properties10ResourcePropertySourceorg.springframework.core.env外部目录(如 /config/application.properties
Profile 特定配置(如 application-dev.properties11ProfileSpecificPropertySourceorg.springframework.boot.envsrc/main/resources/application-{profile}.properties
外置配置文件(如 external-config/application.properties12ExternalConfigPropertySourceorg.springframework.boot.env外置路径(如 /opt/config/application.properties

二、配置源加载流程详解
  1. 初始化 Environment

    • Spring Boot 启动时,通过 SpringApplication 创建 Environment 对象(类型 StandardEnvironment)。
    • Environment 管理所有配置源的集合 PropertySources
  2. 加载引导配置

    • 通过 PropertySourceBootstrapConfiguration 加载 bootstrap.yml/properties(用于配置加密、外部配置文件路径等)。
  3. 逐层加载配置源

    • 使用 PropertySourceLoader 加载不同格式的配置文件(如 YAML、Properties):
      // 例如加载 YAML 文件
      YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
      Resource resource = new ClassPathResource("application.yml");
      PropertySource<?> yamlSource = loader.load("application", resource, 0);
      environment.getPropertySources().addLast(yamlSource);
      
  4. 合并配置源

    • 按优先级顺序合并所有 PropertySource,高优先级覆盖低优先级的同名属性。

三、配置转换过程
  1. 属性解析

    • 通过 ConfigurationPropertySources 将所有 PropertySource 转换为 ConfigurationPropertySource
      // 示例:解析属性路径
      ConfigurationPropertyName name = ConfigurationPropertyName.of("server.port");
      
  2. 绑定到 Bean

    • 使用 Binder 将属性值绑定到 @ConfigurationProperties 注解的 Bean:
      @ConfigurationProperties(prefix = "app")
      public class AppProperties {
          private String name;
          private int timeout;
          // getters/setters
      }
      
      @SpringBootApplication
      @EnableConfigurationProperties(AppProperties.class) // 必须启用
      public class Application {
          public static void main(String[] args) {
              SpringApplication.run(Application.class, args);
          }
      }
      
  3. 类型转换

    • 通过 ConversionService 处理类型转换(如 StringInteger):
      @Bean
      public ConversionService conversionService() {
          GenericConversionService service = new GenericConversionService();
          service.addConverter(String.class, Integer.class, s -> Integer.parseInt(s));
          return service;
      }
      

四、嵌套与替换规则
  1. 变量替换

    • 支持 ${key} 语法引用其他属性:
      # application.properties
      base.url=http://example.com
      api.url=${base.url}/api
      
  2. 优先级覆盖

    • 高优先级配置源的值覆盖低优先级的同名属性:
      # application.properties: server.port=8080
      # 命令行参数:--server.port=9090 → 最终值为 9090
      
  3. 多文档合并

    • 同名属性按加载顺序依次覆盖,最终保留最高优先级的值。

五、配置源对比表
配置源类型位置/来源是否可覆盖典型使用场景代码示例
命令行参数启动参数运行时动态配置java -jar app.jar --server.port=9090
SPRING_APPLICATION_JSON环境变量或系统属性简单 JSON 配置-Dspring.application.json='{ "server": { "port": 9090 } }'
系统环境变量操作系统环境变量生产环境全局配置export SPRING_DATASOURCE_URL=jdbc:mysql://localhost:3306/db
@PropertySource 注解代码指定的资源路径内嵌特定配置文件```java
\n@Configuration\n@PropertySource(“classpath:custom.properties”)\n```
外置配置文件文件系统(如 /config生产环境外部配置/config/application.properties
Profile 特定配置类路径或外置路径不同环境差异化配置application-dev.properties

六、代码示例
1. 系统环境变量覆盖
# 操作系统环境变量设置:
export APP_NAME="ProductionApp"
// 使用 @Value 注入
@Value("${APP_NAME}")
private String appName;
2. 随机属性使用
# application.properties
random.seed=12345
@Value("${random.number}")
private int randomNum; // 自动生成随机数
3. JNDI 配置示例
// JNDI 配置(需容器支持)
@Resource(name = "java:comp/env/jdbc/datasource")
private DataSource dataSource;
4. 外置配置文件激活
# 启动命令指定配置路径:
java -jar app.jar --spring.config.location=file:/opt/config/application.properties
5. Profile 特定配置
# application-dev.properties
spring.datasource.url=jdbc:mysql://localhost:3306/dev
// 启动时指定 Profile:
java -jar app.jar --spring.profiles.active=dev

七、总结表格
配置源类型优先级对应类/接口是否可覆盖典型文件/来源示例
命令行参数SimpleCommandLinePropertySource启动参数--server.port=9090
系统环境变量SystemEnvironmentPropertySource操作系统环境变量export SPRING_DATASOURCE_URL=jdbc:mysql://localhost:3306/db
类路径 application.propertiesPropertiesPropertySourceLoader内置资源路径src/main/resources/application.properties
外置配置文件中低ExternalConfigPropertySource外部文件路径/config/application.properties

关键代码类参考

  • 加载器YamlPropertySourceLoader, PropertiesPropertySourceLoaderorg.springframework.boot.env
  • 环境管理StandardEnvironment, ConfigurableEnvironmentorg.springframework.core.env
  • 绑定机制Binder, ConfigurationPropertyBindingPostProcessororg.springframework.boot.context.properties

通过上述流程,Spring Boot 实现了灵活且可扩展的配置管理能力,开发者可根据需求选择合适的配置源并控制优先级。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱的叹息

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值