propertysourcesplaceholderconfigurer是spring 3.1+推荐的占位符解析器,作为beanfactorypostprocessor在bean实例化前解析${}占位符,从properties文件、环境变量等属性源注入实际值,支持多源加载、默认值及忽略策略。

Spring 通过 PropertySourcesPlaceholderConfigurer 加载外部配置,核心是让 Spring 容器在启动时解析占位符(如 ${db.url}),并从指定的外部资源(如 properties 文件、环境变量、系统属性等)中注入实际值。它本质是一个 BeanFactoryPostProcessor,会在 Bean 实例化前处理占位符。
配置 PropertySourcesPlaceholderConfigurer 的方式
推荐使用 Java 配置(@Configuration)或 XML 配置声明该 Bean。注意:Spring 3.1+ 更推荐用 PropertySourcesPlaceholderConfigurer 替代旧的 PropertyPlaceholderConfigurer,因为它支持更灵活的 PropertySource 层级和顺序。
- Java 配置示例:
@Configuration
public class AppConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
// 指定外部 properties 文件路径(支持 classpath:、file:、http: 等)
configurer.setLocation(new ClassPathResource("application.properties"));
// 可设多个文件,按顺序加载,后加载的覆盖前面同名属性
configurer.setLocations(
new ClassPathResource("application.properties"),
new FileSystemResource("/opt/config/custom.properties")
);
// 允许找不到文件时不报错(默认为 true)
configurer.setIgnoreResourceNotFound(true);
// 是否忽略无法解析的占位符(默认 false,设为 true 则保留 ${xxx} 字符串)
configurer.setIgnoreUnresolvablePlaceholders(false);
return configurer;
}
}
支持的外部配置源类型
PropertySourcesPlaceholderConfigurer 默认只读取 Resource 类型(如 .properties 文件),但可通过扩展支持更多来源:
-
Classpath 资源:如
classpath:config/app.properties -
文件系统路径:如
file:/etc/myapp/config.properties(需确保应用有读取权限) -
系统属性与环境变量:默认已自动注册
systemProperties和systemEnvironment,无需额外配置,可直接用${JAVA_HOME}或${user.name} -
自定义 PropertySource:需继承
PropertySourcesPlaceholderConfigurer并重写postProcessBeanFactory,或在 Spring Boot 中优先使用@ConfigurationProperties+Environment
占位符语法与嵌套解析
支持标准占位符格式,也支持默认值和嵌套表达式(需启用 setIgnoreUnresolvablePlaceholders(false)):
-
${database.url}→ 直接取值 -
${database.url:jdbc:h2:mem:testdb}→ 提供默认值 -
${database.port:8080:#{systemProperties['user.timezone']}}→ 注意:SpEL 表达式(#{...})和占位符(${...})混合时需谨慎,PropertySourcesPlaceholderConfigurer本身不解析 SpEL,需配合PropertySourcesPropertyResolver或使用@Value("#{...}")
与 Spring Boot 的区别说明
Spring Boot 自动配置了 PropertySourcesPlaceholderConfigurer(底层是 ConfigurationPropertySourcesPostProcessor),并默认加载 application.properties、application.yml、命令行参数、环境变量等。若手动定义该 Bean,会覆盖 Boot 的自动配置,需自行保证所有标准源(如 profile-specific 文件)被正确加载。一般情况下,Boot 项目无需显式声明,改用 @ConfigurationProperties 或 @Value 即可。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











