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

Maven多模块Spring Boot项目无法解析test.name配置占位符如何解决

多模块Spring Boot项目无法读取application.yml配置排查方案

1. 配置文件存放与父模块打包类型问题

  • Spring Boot默认仅加载启动类所在子模块的src/main/resources目录下的配置文件,单模块阶段存放在根模块的配置,拆分成多模块后子模块不会自动加载父模块/同级模块的配置。
  • 若父模块的打包类型为pom,默认不会将src/main/resources下的文件打进构件,就算子模块引入父依赖也无法读取到父模块存放的配置。
  • 对应解决方法:
    • 方案1:将需要用到的application.yml直接放到user-service、communication-service等启动类所在子模块的src/main/resources目录下。
    • 方案2:新增专门的公共配置子模块,打包类型设为jar,将通用配置放到该模块的resources目录,所有业务子模块引入该公共配置模块依赖,同时启动类添加@PropertySource注解加载yml配置,需自行实现Yaml配置加载工厂:
      // Yaml配置加载工厂实现
      public class YamlPropertySourceFactory implements PropertySourceFactory {
          @Override
          public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
              return new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource()).get(0);
          }
      }
      
      // 启动类上添加注解
      @SpringBootApplication
      @PropertySource(value = "classpath:application.yml", factory = YamlPropertySourceFactory.class)
      public class UserServiceApplication {
          public static void main(String[] args) {
              SpringApplication.run(UserServiceApplication.class, args);
          }
      }
      

2. 子模块资源打包规则配置缺失

  • 检查子模块pom文件的build节点是否配置了资源过滤规则,若规则排除了yml文件、或未指定resources目录,打包后jar包的BOOT-INF/classes目录下不会包含配置文件。
  • 解决方法:在所有启动类所在子模块的pom中添加资源打包配置:
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.yml</include>
                    <include>**/*.yaml</include>
                    <include>**/*.properties</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
        <!-- 若为可执行jar,需保留spring-boot-maven-plugin插件配置 -->
    </build>
    

3. 多环境配置激活错误

  • 若项目拆分时引入了多环境配置(如application-dev.yml/application-prod.yml),检查启动参数或主配置中spring.profiles.active指定的激活环境,确认test.name配置存在于激活的环境配置文件中。

临时规避方案

可给@Value注解添加默认值避免启动报错:

@Value("${test.name:defaultAppName}")
private String testName;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 21:15:05