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

Spring Boot如何读取application-test.properties配置并解决占位符解析错误

问题原因

  1. 你编写的PropertiesUtils类中的initProperties()方法仅在内部创建了PropertySourcesPlaceholderConfigurer实例,既没有将该实例注册为Spring容器的Bean,也没有调用逻辑触发该方法执行,Spring无法感知到你指定的属性文件配置,因此无法解析${machineName}占位符。
  2. Spring Boot本身默认支持按激活的profile自动加载application-{profile}.properties配置,你手动编写的配置类逻辑本身是冗余的,错误的写法反而阻断了默认属性加载流程。

解决办法

方案1(推荐,无需保留自定义配置类)

直接删除你编写的PropertiesUtils配置类即可:

  • Spring Boot默认会自动扫描src/main/resources目录下的application.properties、以及对应激活profile的application-{profile}.properties文件,只要spring.profiles.active=test配置生效,machineName属性会被自动加载,@Value注入可以正常生效。
  • 若担心profile未生效,可在启动参数中添加-Dspring.profiles.active=test,或在application.properties中新增配置spring.profiles.active=test。

方案2(保留手动配置逻辑)

修改PropertiesUtils类,将属性配置器注册为Spring Bean:

@Configuration
public class PropertiesUtils {

    @Bean
    public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        String activeProfile = System.getProperty("spring.profiles.active");
        if (activeProfile == null) {
            activeProfile = "test";
        }
        PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
        Resource[] resources = new ClassPathResource[] {
            new ClassPathResource("application.properties"),
            new ClassPathResource("application-" + activeProfile + ".properties")
        };
        propertySourcesPlaceholderConfigurer.setLocations(resources);
        return propertySourcesPlaceholderConfigurer;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 00:18:02