feat:更新springboot技巧文档

This commit is contained in:
2026-01-05 22:23:41 +08:00
parent 939cf05db2
commit b6669a1731

View File

@@ -305,3 +305,55 @@ public class UserDTO {
private String mobile;
}
```
# 四、ConfigurationProperties注解
  @ConfigurationProperties 是 Spring Boot 提供的核心注解,用于将配置文件(如 application.yml/application.properties中的属性批量绑定到 Java 类的字段上,相比 @Value 注解,它更适合管理一组有层级、有前缀的配置,代码更整洁、可维护性更高。
## 4.1 配置文件
```yml
app:
name: SpringBootDemo
version: 1.0.0
author:
name: 张三
age: 25
servers:
- 192.168.1.100
- 192.168.1.101
- 192.168.1.102
```
## 4.2 配置属性类
```java
@Component
@ConfigurationProperties(prefix = "app")
@Getter
@Setter
public class AppProperties {
// 对应 app.name
private String name;
// 对应 app.version
private String version;
// 嵌套属性 - 对应 app.author
private Author author;
// 集合属性 - 对应 app.servers
private List<String> servers;
@Getter
@Setter
public static class Author {
private String name;
private Integer age;
}
}
```
&emsp;&emsp;属性类支持嵌套和集合属性。
## 4.3 使用
&emsp;&emsp;在Service或相应地方注入即可
```java
@Autowired
private AppProperties appProperties;
```