You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SpringBoot使用@PropertySource导入属性时如何自动添加属性名前缀

在SpringBoot中为@PropertySource加载的配置自动添加前缀

针对你需要为自动生成、不可修改的.properties文件属性统一添加前缀以避免冲突的需求,可以通过自定义PropertySourceFactory扩展@PropertySource的功能来实现,无需额外编写大量配置读取代码。

实现步骤

1. 自定义前缀处理的PropertySourceFactory

创建一个工厂类,继承Spring默认的DefaultPropertySourceFactory,在加载属性时为每个key自动添加指定前缀:

import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;

import java.util.Properties;

public class PrefixedPropertySourceFactory extends DefaultPropertySourceFactory {

    private final String prefix;

    public PrefixedPropertySourceFactory(String prefix) {
        // 确保前缀以.结尾,避免拼接时出现格式错误
        this.prefix = prefix.endsWith(".") ? prefix : prefix + ".";
    }

    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IllegalArgumentException {
        PropertySource<?> originalSource = super.createPropertySource(name, resource);
        if (originalSource instanceof PropertiesPropertySource propertiesSource) {
            Properties prefixedProperties = new Properties();
            // 遍历原属性集合,为每个key添加前缀后存入新Properties
            propertiesSource.getSource().forEach((key, value) ->
                    prefixedProperties.put(prefix + key, value));
            return new PropertiesPropertySource(originalSource.getName(), prefixedProperties);
        }
        return originalSource;
    }
}

2. 在@PropertySource中指定自定义工厂

修改你的配置类,通过@PropertySource的factory属性指定自定义工厂,并传入对应前缀(可以用SpEL动态从文件名提取前缀,更通用):

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

@Configuration
@PropertySource(
        value = "classpath:karmiel.properties",
        factory = PrefixedPropertySourceFactory.class,
        // 从文件名中提取前缀(自动去掉.properties后缀)
        arguments = "#{T(java.io.File).nameWithoutExtension('karmiel.properties')}"
)
public class KarmielConfig {
    // 后续可通过@Value("${karmiel.keystore}")、@Value("${karmiel.username-token}")等读取属性
}

3. 批量处理其他配置文件

对于类似的sderot.properties,只需复制配置类并修改文件名参数即可:

@Configuration
@PropertySource(
        value = "classpath:sderot.properties",
        factory = PrefixedPropertySourceFactory.class,
        arguments = "#{T(java.io.File).nameWithoutExtension('sderot.properties')}"
)
public class SderotConfig {
    // 通过@Value("${sderot.xxx}")读取对应属性
}

补充说明

  • 若不需要动态提取前缀,可直接硬编码传入,比如arguments = "'karmiel'"
  • 该实现仅针对PropertiesPropertySource(Spring加载.properties文件的默认类型),确保兼容性
  • 完全依托Spring原生的@PropertySource扩展,无需额外编写配置读取逻辑,符合你减少代码量的需求

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 10:25:34