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

Spring Boot多模块下同名Profile配置文件合并问题

Spring Boot多模块下同名Profile配置文件合并问题

你遇到的这个问题其实是Spring Boot 2.3.x版本默认配置加载逻辑导致的——对于同名的Profile配置文件,Spring Boot默认只会加载其中一份(加载顺序取决于classpath优先级,通常依赖库的配置会先被加载,你的业务模块配置可能被覆盖或未被识别),不会自动合并两份文件的属性。

要实现你想要的“合并模式”,这里有两个实用方案,你可以根据场景选择:

方案一:修改配置文件名,通过多Profile导入实现合并(推荐,无代码改动)

这个方法最简单,不需要编写代码,只需调整配置文件命名:

  1. 把核心库的application-cache.properties改名为application-core-cache.properties
  2. 把业务模块的application-cache.properties改名为application-app-cache.properties
  3. 在主配置文件application.properties里修改Profile导入配置:
spring.profiles.include=core-cache,app-cache

这样Spring Boot会加载这两个Profile的配置文件,自动合并所有属性——核心库的cache.value1、cache.value2和业务模块的additional.value都会生效。

方案二:自定义配置加载器,实现同名文件属性合并(适合必须保留文件名的场景)

如果必须保留application-cache.properties这个文件名,可以通过自定义Spring属性加载器实现合并:
在业务模块中创建一个配置类,手动加载所有classpath下的同名配置文件并开启合并:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;

@Configuration
public class CachePropertyMergeConfig {

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyConfigurer() {
        PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
        // 加载所有classpath下的application-cache.properties(包含核心库和业务模块的)
        configurer.setLocations(new ClassPathResource("classpath*:application-cache.properties"));
        // 开启属性合并模式
        configurer.setMergeProperties(true);
        // 允许找不到资源(避免部分环境下缺少文件报错)
        configurer.setIgnoreResourceNotFound(true);
        return configurer;
    }
}

这个配置类会合并所有找到的application-cache.properties文件属性,业务模块的新属性会被添加;如果业务模块写了和核心库同名的属性,会覆盖核心库的配置(不需要覆盖的话,别写同名属性即可)。

备注:内容来源于stack exchange,提问作者Andrei Hryshanovich

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.21 08:54:34