最常用且推荐的方式是使用 spring boot 的 @configurationproperties 注解。它支持类型安全、松散绑定、校验和元数据提示,比传统方式更简洁可靠;需准备 properties 文件、创建带 @configurationproperties 和 @component 的实体类、启用配置绑定,并可直接注入使用。

Java 中将外部 properties 配置文件中的属性自动绑定到实体类对象,最常用且推荐的方式是使用 Spring Boot 的 @ConfigurationProperties 注解。它支持类型安全、松散绑定、校验和元数据提示,比传统的 PropertyPlaceholderConfigurer 或手动 Properties.load() 更简洁可靠。
1. 准备配置文件(如 application.properties 或自定义 xxx.properties)
在 src/main/resources 下新建一个 properties 文件,例如 app-config.properties:
app.name=MyApp<br>app.version=2.3.1<br>app.timeout=5000<br>app.features.cache=true<br>app.features.retry.max-attempts=3
注意:支持嵌套结构(用点号分隔),Spring 会自动映射到嵌套对象。
2. 创建对应实体类并启用 @ConfigurationProperties
实体类需满足 JavaBean 规范(提供无参构造器 + getter/setter),并添加 @ConfigurationProperties 和 @Component(或通过 @EnableConfigurationProperties 显式注册):
- 类上加
@ConfigurationProperties(prefix = "app"),指定配置前缀 - 加上
@Component让 Spring 扫描并注入该 Bean - 建议搭配
@Validated和字段校验注解(如@NotBlank、@Min)提升健壮性
@Component<br>@ConfigurationProperties(prefix = "app")<br>@Validated<br>public class AppConfig {<br> private String name;<br> private String version;<br> private int timeout;<br> private Features features = new Features();<br> // getter/setter...<br><br> public static class Features {<br> private boolean cache;<br> private int maxAttempts;<br> // getter/setter...<br> }<br>}
3. 启用配置属性绑定(Spring Boot 2.2+ 默认开启)
确保项目已引入 spring-boot-configuration-processor(用于生成配置元数据,非必需但推荐):
<dependency><br><groupid>org.springframework.boot</groupid><br><artifactid>spring-boot-configuration-processor</artifactid><br><optional>true</optional><br></dependency>
同时,在 application.properties 中启用配置文件加载(如果用的是自定义文件名):
spring.config.import=classpath:app-config.properties
或者用 @PropertySource(适用于 Spring Framework 或老版本 Boot):
@ConfigurationProperties(prefix = "app")<br>@PropertySource("classpath:app-config.properties")<br>@Component<br>public class AppConfig { ... }
4. 在其他 Bean 中直接注入使用
Spring 容器会自动完成绑定,你只需像普通 Bean 一样注入即可:
@Service<br>public class AppService {<br> private final AppConfig appConfig;<br><br> public AppService(AppConfig appConfig) {<br> this.appConfig = appConfig;<br> }<br><br> public void printConfig() {<br> System.out.println(appConfig.getName()); // MyApp<br> System.out.println(appConfig.getFeatures().isCache()); // true<br> }<br>}
绑定发生在应用上下文刷新阶段,支持 reload(配合 @RefreshScope 可实现运行时刷新,需整合 Spring Cloud Config 或 Actuator)。
不复杂但容易忽略:确保属性名与配置键严格匹配(支持驼峰、中划线、下划线等松散绑定),字段类型必须可转换(如字符串转 int),否则启动失败并抛出 BindException。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











