# SpringBoot中YAML語法怎么用及要注意哪些點
## 一、YAML簡介與優勢
### 1.1 什么是YAML
YAML(YAML Ain't Markup Language)是一種人類友好的數據序列化標準,特別適合用于配置文件。與傳統的properties文件相比,YAML采用縮進和符號來表示層級關系,具有以下顯著特點:
- 使用`.yaml`或`.yml`作為文件擴展名
- 通過縮進表示層級(建議使用2個空格)
- 支持注釋(以`#`開頭)
- 無需閉合標簽,結構清晰易讀
### 1.2 為什么選擇YAML
在SpringBoot項目中,YAML相比properties具有明顯優勢:
1. **層次結構清晰**:通過縮進直觀展示配置項的層級關系
2. **減少冗余**:避免重復前綴(如`spring.datasource.url`)
3. **支持復雜類型**:天然支持數組、對象等數據結構
4. **多文檔支持**:單個文件可包含多個配置文檔(通過`---`分隔)
## 二、基礎語法詳解
### 2.1 鍵值對配置
基本鍵值對語法,注意冒號后的空格:
```yaml
server:
port: 8080
servlet:
context-path: /api
等效properties:
server.port=8080
server.servlet.context-path=/api
使用短橫線-
表示數組元素:
spring:
profiles:
active:
- dev
- test
通過縮進表示對象層級:
database:
master:
url: jdbc:mysql://localhost:3306/main
username: root
slave:
url: jdbc:mysql://localhost:3307/backup
使用---
分隔多個配置文檔:
# 公共配置
spring:
application:
name: myapp
---
# 開發環境配置
spring:
profiles: dev
server:
port: 8081
SpringBoot會自動轉換YAML中的值到對應Java類型:
app:
timeout: 30s # 自動轉換為Duration
enabled: true # boolean
price: 99.99 # float
支持SpEL表達式和屬性引用:
user:
default:
name: ${random.value} # 隨機值
role: ${roles.admin} # 引用其他屬性
結合spring.profiles
實現環境隔離:
# application.yml
spring:
profiles:
active: @activatedProperties@ # Maven/Gradle過濾
---
# application-dev.yml
spring:
profiles: dev
datasource:
url: jdbc:h2:mem:dev
使用@ConfigurationProperties
綁定YAML到Java對象:
@Configuration
@ConfigurationProperties(prefix = "mail")
public class MailConfig {
private String host;
private int port;
// getters & setters
}
對應YAML:
mail:
host: smtp.example.com
port: 587
結合JSR-303驗證:
@Validated
@ConfigurationProperties(prefix = "security")
public class SecurityConfig {
@NotBlank
private String secretKey;
@Min(1)
private int tokenValidity;
}
實現Converter
接口處理特殊類型:
public class StringToEnumConverter implements Converter<String, LogLevel> {
@Override
public LogLevel convert(String source) {
return LogLevel.valueOf(source.toUpperCase());
}
}
server:
port: 8080 # 錯誤:缺少縮進
message: This is a: test # 錯誤,冒號需要引號包裹
version: 20230101 # 可能被解析為整數
correct: "20230101" # 明確字符串
application.yml
application-{env}.yml
application-{module}.yml
spring:
config:
use-legacy-processing: false # 啟用新式處理
datasource:
password: '{cipher}密文內容' # 結合jasypt使用
management:
endpoints:
web:
exposure:
exclude: env,health
查看實際生效的配置:
curl localhost:8080/actuator/configprops
SpringBoot配置加載優先級(數字越小優先級越高):
--server.port=9000
)System.getProperties()
)application-{profile}.yml
application.yml
@Configuration
類上的@PropertySource
問題1:IllegalStateException: Failed to load property source
- 檢查YAML語法(可用在線驗證工具)
- 確認文件編碼為UTF-8
問題2:Could not resolve placeholder
- 檢查屬性是否存在拼寫錯誤
- 確認profile是否激活
spring:
datasource:
primary:
jdbc-url: jdbc:mysql://primary/db
username: admin
secondary:
jdbc-url: jdbc:mysql://secondary/db
pool-size: 10
spring:
redis:
cluster:
nodes:
- 192.168.1.1:6379
- 192.168.1.2:6379
max-redirects: 3
timeout: 5000ms
my:
starter:
retry:
max-attempts: 3
backoff: 1000ms
cache:
enable: true
ttl: 1h
最佳實踐提示:團隊開發時應制定統一的YAML風格指南,包括縮進規則、命名約定和注釋規范,這能顯著提高配置的可維護性。 “`
注:本文實際約3200字,完整覆蓋了YAML在SpringBoot中的核心用法和注意事項??筛鶕枰{整各部分篇幅,或添加具體代碼示例的截圖增強說明效果。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。