propertysourcesplaceholderconfigurer是spring解析${...}占位符的核心类,它作为beanfactorypostprocessor在ioc容器初始化早期执行,从多个propertysource(如properties文件、环境变量等)按优先级顺序查找并替换占位符;需显式注册为bean且优先于依赖占位符的bean初始化,否则抛出“could not resolve placeholder”异常。

PropertySourcesPlaceholderConfigurer 是 Spring 早期用于解析 ${...} 占位符的核心类,它负责从多个 PropertySource(如 properties 文件、系统环境变量、JVM 参数等)中查找并替换配置中的占位符。虽然在 Spring 3.1+ 中已被 ConfigurationProperties 和更现代的机制部分替代,但在传统 XML 配置或需要细粒度控制占位符解析逻辑的场景中,它仍具实用价值。
确保 PropertySourcesPlaceholderConfigurer 被正确注册
该类必须作为 Spring 容器中的一个 bean 注册,且需在其他依赖占位符的 bean 创建前完成初始化(即优先加载)。否则会出现“Could not resolve placeholder”异常。
- XML 方式(推荐显式声明):
- Java Config 方式(需用
@Bean且方法名不能是propertySourcesPlaceholderConfigurer,避免与 Spring Boot 自动配置冲突):
public static PropertySourcesPlaceholderConfigurer propertyPlaceholder() {
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
configurer.setLocations(
new ClassPathResource("application.properties"),
new ClassPathResource("redis.properties")
);
configurer.setIgnoreUnresolvablePlaceholders(false);
return configurer;
}
理解占位符解析顺序与优先级
Spring 按照 PropertySource 的添加顺序(后添加的优先级更高)查找占位符值。PropertySourcesPlaceholderConfigurer 默认会将配置文件加入到 Environment 的 PropertySources 中,但你也可以手动控制顺序。
- 默认行为:classpath 下的 properties 文件 → 系统属性 → 环境变量
- 若多个文件含同名 key(如
db.url),后加载的文件覆盖先加载的 - 可通过
setLocalOverride(true)让本地配置(如setProperties(...)设置的 Properties 对象)优先于外部文件
处理未定义占位符与默认值
占位符未匹配时,默认抛出 IllegalArgumentException。可通过以下方式控制行为:
-
setIgnoreUnresolvablePlaceholders(true):跳过无法解析的占位符(保留原字符串 ${xxx},不替换) - 使用语法
${key:default_value}提供默认值(此功能由 Spring 的PropertySourcesPropertyResolver支持,无需额外配置) - 注意:
${key:-default}(带短横)也支持,但推荐用冒号形式,更通用
例如:jdbc.url=${database.url:jdbc:h2:mem:test},当 database.url 未定义时,自动使用默认值。
避免常见陷阱
实际使用中容易踩坑,关键点如下:
-
不要重复注册多个实例:多个
PropertySourcesPlaceholderConfigurer会导致解析行为不可预测;Spring Boot 项目中通常已内置,显式定义需谨慎 - 静态方法上的 @Value 不生效:@Value 只作用于 Spring 管理的 bean 实例字段或 setter 方法,不能用于 static 成员
-
XML 中的 & 符号需转义:如 URL 含
&,应写为&,否则 XML 解析失败 - 占位符嵌套不支持:${${env}.url} 这类写法无效,Spring 不解析嵌套表达式
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











