@PropertySources可一次性声明多个外部配置文件,是@PropertySource的容器注解,需配合@Configuration或@Component使用,支持classpath:和file:路径,同名key按声明顺序覆盖,缺失文件默认启动失败,可设ignoreResourceNotFound=true容错,并推荐与@ConfigurationProperties结合实现类型安全绑定。

可以直接用 @PropertySources 一次性声明多个外部配置文件,比重复写多个 @PropertySource 更清晰、更规范。
@PropertySources 基本用法
它本质是 @PropertySource 的容器注解,接受一个数组,每个元素是一个 @PropertySource。必须配合 @Configuration 或 @Component 类使用。
- 路径支持
classpath:(类路径下)和file:(绝对或相对文件系统路径) - 多个文件中同名 key,默认按声明顺序覆盖:后加载的会覆盖先加载的
- 若某个文件不存在,且未设
ignoreResourceNotFound = true,启动直接失败
加载 classpath 下多个 .properties 文件
比如把数据库、缓存、消息队列的配置拆成三个文件:
datasource.propertiesredis.propertiesrabbitmq.properties
在配置类中统一引入:
@Configuration
@PropertySources({
@PropertySource("classpath:datasource.properties"),
@PropertySource("classpath:redis.properties"),
@PropertySource("classpath:rabbitmq.properties")
})
public class ExternalConfig {
// 可配合 @Value 或 @ConfigurationProperties 使用
}
安全加载 + 指定编码
生产环境建议显式设置 encoding 防止中文乱码,并对非必需文件开启 ignoreResourceNotFound:
@Configuration
@PropertySources({
@PropertySource(
value = "classpath:app-custom.properties",
encoding = "UTF-8",
ignoreResourceNotFound = true
),
@PropertySource("classpath:app-default.properties")
})
public class AppConfig { }
这样即使 app-custom.properties 缺失,应用仍能用 app-default.properties 启动。
配合 @ConfigurationProperties 绑定结构化配置
推荐将分组配置与 @ConfigurationProperties 结合,提升可读性和类型安全:
@Component
@PropertySource("classpath:mail.properties")
@ConfigurationProperties(prefix = "mail.server")
public class MailServerConfig {
private String host;
private int port;
private String username;
// getter/setter
}
注意:@PropertySource 必须先加载文件,@ConfigurationProperties 才能从中绑定属性;不能用 @PropertySources 直接套在 @ConfigurationProperties 类上——需确保类本身被 Spring 扫描到(如加 @Component),且 @PropertySource 作用于同一类或其父配置类。


















