spring boot加载自定义配置文件推荐使用spring.config.import(2.4+首选),支持properties/yml并参与环境刷新;其次可用@configurationproperties+@propertysource绑定结构化配置;避免直接在启动类或service上用@propertysource;可结合profiles按环境动态导入。

Spring Boot 加载自定义属性配置文件有明确、主流且推荐的几种方式,核心在于“让配置被 Spring 环境识别并注入”,而不是简单地把文件放进去就自动生效。关键看你想在哪个阶段加载、是否影响自动配置、以及配置是单个值还是结构化对象。
用 spring.config.import 指定额外配置文件(推荐,2.4+ 版本首选)
这是目前最简洁、最符合 Spring Boot 原生机制的方式,支持 properties/yml,且能参与环境刷新和自动配置生效流程。
- 在 application.properties 或 application.yml 中添加:
application.properties:spring.config.import=classpath:config/db-config.properties,classpath:config/oss-config.yml
application.yml:
spring:<br> config:<br> import:<br> - "classpath:config/db-config.properties"<br> - "classpath:config/oss-config.yml"
- 配置文件需放在
src/main/resources/config/目录下,如db-config.properties内容为:spring.datasource.url=jdbc:mysql://localhost:3306/test<br>spring.datasource.username=root
- 这些配置会像 application.properties 一样被加载进 Environment,可直接用
@Value或@ConfigurationProperties注入。
用 @ConfigurationProperties + @PropertySource 绑定结构化配置(适合模块化管理)
当你有一组逻辑相关的配置(比如远程服务地址、超时参数),建议封装成配置类,提升可读性和类型安全。
- 新建
src/main/resources/config/remote.properties:
remote.host=api.example.com<br>remote.timeout=5000<br>remote.retries=3
- 创建配置类:
@Configuration<br>@ConfigurationProperties(prefix = "remote")<br>@PropertySource("classpath:config/remote.properties")<br>@Component<br>public class RemoteProperties {<br> private String host;<br> private int timeout;<br> private int retries;<br> // getter/setter
- 使用时直接
@Autowired RemoteProperties remoteProps;即可获取完整对象。 - 注意:Spring Boot 2.4+ 后,
@PropertySource不再支持 yml 文件,仅限 properties;若要用 yml,请改用spring.config.import。
避免在启动类或 Service 上直接用 @PropertySource(不推荐)
虽然语法上可行,但存在明显局限:
- 如果写在
@SpringBootApplication类上,配置加载太晚,无法影响自动配置(比如 DataSource 初始化失败); - 如果写在某个
@Service类上,只对该 Bean 生效,其他地方无法共享; - 编码耦合度高,不符合配置集中管理原则。
除非是极少数临时调试场景,否则不建议采用这种方式。
按环境加载不同自定义配置(配合 profiles 使用)
你可以把自定义配置也按 profile 拆分,实现开发/测试/生产差异化:
- 新建:
src/main/resources/config/app-dev.properties和config/app-prod.properties; - 在主配置中激活 profile:
spring.profiles.active=dev; - 再通过
spring.config.import=classpath:config/app-${spring.profiles.active}.properties动态导入。
这样既能复用 import 机制,又能保持环境隔离,比硬编码路径更灵活可靠。











