最常用且推荐的方式是通过@ConfigurationProperties绑定配置,辅以@Value或@PropertySource按需使用;需确保配置文件规范、类绑定正确,并建议启用元数据支持。

在 Spring Boot 中读取自定义属性配置值,最常用且推荐的方式是通过 @ConfigurationProperties 绑定配置,辅以 @Value 或 @PropertySource 按需使用。关键在于配置文件格式规范、类绑定正确、启用元数据支持(可选但建议)。
使用 @ConfigurationProperties 绑定配置类
这是类型安全、可校验、支持松散绑定的首选方式。
- 在
application.yml(或.properties)中定义自定义配置,例如:
myapp:
name: demo-service
timeout: 5000
features:
enable-cache: true
max-retry: 3
- 新建一个 Java 类,用
@ConfigurationProperties注解,并指定前缀(如"myapp"):
@Component
@ConfigurationProperties(prefix = "myapp")
@Data // 使用 Lombok 简化 getter/setter
public class MyAppProperties {
private String name;
private int timeout;
private Features features;
@Data
public static class Features {
private boolean enableCache; // 自动匹配 enable-cache(松散绑定)
private int maxRetry;
}
}
- 确保在启动类或配置类上启用配置属性扫描(Spring Boot 2.2+ 默认启用;若手动管理需加
@EnableConfigurationProperties(MyAppProperties.class)) - 依赖
spring-boot-configuration-processor(开发期生成configuration-metadata.json,支持 IDE 提示和校验)
用 @Value 直接注入单个属性值
适合简单、零散、不需要复用或校验的场景。
- 直接在字段或方法参数上使用
@Value("${myapp.name:default-name}"),冒号后为默认值(必填,否则启动失败) - 支持 SpEL 表达式,例如:
@Value("#{systemProperties['os.name']}") - 不支持复杂嵌套对象,也不做类型转换容错(如字符串转布尔失败会报错)
加载非标准配置文件(如 custom-config.yml)
当配置不在 application.yml 中时,需显式引入。
立即学习“Java免费学习笔记(深入)”;
- 使用
@PropertySource(仅支持.properties,不支持 YAML) - 推荐用
@ConfigurationProperties+@ImportResource或更灵活的方式:在application.yml中通过spring.config.import引入:
spring:
config:
import: classpath:custom-config.yml
- 然后照常用
@ConfigurationProperties绑定即可
验证与调试小技巧
避免常见错误的关键点:
- 确认配置 key 的大小写和连字符是否符合松散绑定规则(
enable-cache→enableCache) - 检查类是否被 Spring 容器管理(加
@Component或注册为@Bean) - 启动时加
--debug查看自动配置报告,确认ConfigurationPropertiesBindingPostProcessor是否生效 - 访问
/actuator/configprops(需引入spring-boot-starter-actuator)查看已绑定的配置详情


















