Spring Boot如何读取application-test.properties配置并解决占位符解析错误
问题原因
- 你编写的
PropertiesUtils类中的initProperties()方法仅在内部创建了PropertySourcesPlaceholderConfigurer实例,既没有将该实例注册为Spring容器的Bean,也没有调用逻辑触发该方法执行,Spring无法感知到你指定的属性文件配置,因此无法解析${machineName}占位符。 - 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
相关产品推荐
相关产品推荐

