1. 基本语法
YAML使用缩进来表示层级关系,通常使用空格进行缩进(推荐使用2个空格)。
基本语法示例:
key: value
nested:
key: value
list:
- item1
- item2
2. 配置文件命名
在Spring Boot中,YAML配置文件通常命名为 application.yml
,放置在 src/main/resources
目录下。
3. 常见配置示例
3.1 数据源配置
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: user
password: pass
driver-class-name: com.mysql.cj.jdbc.Driver
3.2 服务器配置
server:
port: 8080
servlet:
context-path: /api
3.3 日志配置
logging:
level:
root: INFO
org.springframework.web: DEBUG
file:
name: app.log
3.4 自定义属性
app:
name: My Application
description: This is my Spring Boot application
version: 1.0.0
4. 多环境配置
YAML允许在单个文件中定义多个配置profiles:
spring:
profiles:
active: dev
---
spring:
config:
activate:
on-profile: dev
server:
port: 8080
---
spring:
config:
activate:
on-profile: prod
server:
port: 80
5. 列表和数组
YAML支持列表和数组的简洁表示:
my:
servers:
- dev.example.com
- prod.example.com
ports: [8080, 8081, 8082]
6. 复杂对象
YAML可以表示复杂的嵌套结构:
person:
name: John Doe
age: 30
address:
street: 123 Main St
city: New York
country: USA
hobbies:
- reading
- swimming
7. 使用占位符和引用
YAML支持使用占位符和引用其他配置值:
app:
name: MyApp
description: Welcome to ${app.name}
db:
connection: "Database connection for ${app.name}"
8. 外部化配置
Spring Boot支持从外部YAML文件加载配置:
spring:
config:
import: optional:file:./config/app-config.yml
9. 配置属性类
可以创建配置属性类来映射YAML配置:
@ConfigurationProperties(prefix = "app")
@Component
public class AppProperties {
private String name;
private String description;
// getters and setters
}
对应的YAML:
app:
name: MyApp
description: App Description
10. 集合和Map的配置
YAML可以轻松配置复杂的集合和Map结构:
app:
users:
- name: user1
role: ADMIN
- name: user2
role: USER
settings:
timeout: 3000
retries: 5
11. 使用锚点和别名
YAML支持使用锚点(&)和别名(*)来重用配置:
defaults: &defaults
timeout: 30
retries: 3
service1:
<<: *defaults
url: http://service1.example.com
service2:
<<: *defaults
url: http://service2.example.com
12. 激活profiles
可以在YAML中指定要激活的profiles:
spring:
profiles:
active:
- dev
- local
13. 条件配置
使用SpEL表达式进行条件配置:
my:
property: "This is always set"
conditional-property: "${my.property} (set only if 'dev' profile is active)"
14. 使用环境变量
YAML配置可以引用环境变量:
app:
secret: ${APP_SECRET}
15. 配置随机值
Spring Boot提供了生成随机值的功能:
app:
secret: ${random.uuid}
number: ${random.int}