You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Spring Boot中如何同时使用application.yml与sensitive-data.yml的属性?

在Spring Boot中同时加载多个YAML配置文件的方案

没问题,在Spring Boot里同时加载application.ymlsensitive-data.yml这类多配置文件完全可行,我给你分享几种最常用的方案,根据你的Spring Boot版本和实际场景来选就行:

1. 用Spring Boot 2.4+推荐的spring.config.import(最简便)

从Spring Boot 2.4开始,官方推荐用spring.config.import来导入额外配置文件,不需要写任何Java代码,直接在主配置文件里配置即可:

application.yml中添加以下内容:

spring:
  config:
    import: classpath:sensitive-data.yml
  • 原理:Spring Boot会自动加载指定路径下的YAML文件,将其属性合并到全局环境中
  • 注意:如果两个文件有同名属性application.yml的属性会覆盖sensitive-data.yml的(因为主配置文件优先级更高)
  • 路径说明:classpath:表示文件放在src/main/resources目录下,如果是外部文件可以用file:/path/to/sensitive-data.yml

2. 自定义YamlPropertySourceFactory配合@PropertySource(兼容旧版本)

如果你的Spring Boot版本低于2.4,或者需要更灵活的配置加载逻辑,可以用@PropertySource注解,但默认它不支持YAML格式,所以需要自定义一个属性源工厂:

第一步:创建YAML属性源工厂类

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;

import java.io.IOException;
import java.util.Properties;

public class YamlPropertySourceFactory implements PropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(resource.getResource());
        Properties properties = factory.getObject();
        // 用文件名作为属性源名称,方便排查问题
        return new PropertiesPropertySource(resource.getResource().getFilename(), properties);
    }
}

第二步:在配置类上添加注解

创建一个配置类(或者用已有的配置类),添加@PropertySource注解指定YAML文件和自定义工厂:

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@PropertySource(value = "classpath:sensitive-data.yml", factory = YamlPropertySourceFactory.class)
public class AdditionalConfig {
}

这样Spring容器启动时就会加载sensitive-data.yml里的属性,和application.yml的属性合并使用。

3. 通过启动参数/环境变量加载(部署时动态配置)

如果需要在部署时灵活指定额外配置文件,可以用启动参数或者环境变量:

启动参数方式

启动应用时添加以下参数:

java -jar your-app.jar --spring.config.additional-location=classpath:sensitive-data.yml

环境变量方式

设置环境变量(Linux/macOS):

export SPRING_CONFIG_ADDITIONAL_LOCATION=classpath:sensitive-data.yml

然后启动应用即可。


内容的提问来源于stack exchange,提问作者mpontsasa

火山引擎 最新活动