配置文件详解
2026/1/15大约 3 分钟SpringSpring BootJava微服务后端
配置文件详解
配置文件类型
Spring Boot 支持两种配置文件格式:
| 格式 | 文件名 | 特点 |
|---|---|---|
| Properties | application.properties | 传统格式,简单直观 |
| YAML | application.yml | 层级结构,更易读 |
Properties 格式
# application.properties
server.port=8080
server.servlet.context-path=/api
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456YAML 格式
# application.yml
server:
port: 8080
servlet:
context-path: /api
spring:
datasource:
url: jdbc:mysql://localhost:3306/test
username: root
password: 123456推荐
推荐使用 YAML 格式,层级结构更清晰,支持列表和复杂对象。
配置优先级
Spring Boot 按以下顺序加载配置(优先级从高到低):
常用配置方式
# 1. 命令行参数(最高优先级)
java -jar app.jar --server.port=9090
# 2. 环境变量
export SERVER_PORT=9090
# 3. 配置文件
# application.yml
server:
port: 8080Profile 多环境配置
定义 Profile 配置文件
# 目录结构
src/main/resources/
├── application.yml # 公共配置
├── application-dev.yml # 开发环境
├── application-test.yml # 测试环境
└── application-prod.yml # 生产环境公共配置
# application.yml
spring:
profiles:
active: dev # 默认激活 dev 环境
# 公共配置
logging:
pattern:
console: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n"环境配置
# application-dev.yml
server:
port: 8080
spring:
datasource:
url: jdbc:mysql://localhost:3306/dev_db
username: dev
password: dev123
logging:
level:
root: DEBUG# application-prod.yml
server:
port: 80
spring:
datasource:
url: jdbc:mysql://prod-db:3306/prod_db
username: ${DB_USERNAME}
password: ${DB_PASSWORD}
logging:
level:
root: WARN激活 Profile
# 方式1:配置文件
spring:
profiles:
active: prod
# 方式2:命令行参数
java -jar app.jar --spring.profiles.active=prod
# 方式3:环境变量
export SPRING_PROFILES_ACTIVE=prod
# 方式4:JVM 参数
java -Dspring.profiles.active=prod -jar app.jarProfile 分组
# application.yml
spring:
profiles:
group:
prod:
- prod
- prod-db
- prod-mq
dev:
- dev
- dev-db配置属性绑定
@Value 注解
@Component
public class MyComponent {
@Value("${server.port}")
private int port;
@Value("${app.name:DefaultApp}") // 默认值
private String appName;
@Value("${app.servers}") // 列表
private List<String> servers;
@Value("#{${app.map}}") // Map
private Map<String, String> map;
}app:
name: MyApp
servers: server1,server2,server3
map: "{key1: 'value1', key2: 'value2'}"@ConfigurationProperties
@Component
@ConfigurationProperties(prefix = "app")
public class AppProperties {
private String name;
private int timeout;
private List<String> servers;
private Map<String, String> headers;
private Security security;
// getters and setters
public static class Security {
private boolean enabled;
private String secret;
// getters and setters
}
}app:
name: MyApp
timeout: 30
servers:
- server1
- server2
headers:
Content-Type: application/json
Accept: application/json
security:
enabled: true
secret: my-secret-key配置校验
@Component
@ConfigurationProperties(prefix = "app")
@Validated // 启用校验
public class AppProperties {
@NotBlank
private String name;
@Min(1)
@Max(3600)
private int timeout;
@NotEmpty
private List<String> servers;
// getters and setters
}配置加密
使用 Jasypt
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.5</version>
</dependency># application.yml
jasypt:
encryptor:
password: ${JASYPT_PASSWORD} # 加密密钥
spring:
datasource:
password: ENC(加密后的密码)# 加密密码
java -cp jasypt.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI \
input="mypassword" password="secretkey" algorithm=PBEWithMD5AndDES配置刷新
使用 @RefreshScope
@RestController
@RefreshScope // 支持配置刷新
public class ConfigController {
@Value("${app.message}")
private String message;
@GetMapping("/message")
public String getMessage() {
return message;
}
}配合 Spring Cloud Config 或 Nacos 使用,可以实现配置热更新。
常用配置项
服务器配置
server:
port: 8080
servlet:
context-path: /api
tomcat:
max-threads: 200
min-spare-threads: 10
max-connections: 10000
accept-count: 100数据源配置
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
hikari:
maximum-pool-size: 20
minimum-idle: 5
idle-timeout: 30000
connection-timeout: 30000日志配置
logging:
level:
root: INFO
com.example: DEBUG
org.springframework: WARN
file:
name: logs/app.log
max-size: 10MB
max-history: 30
pattern:
console: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n"小结
Spring Boot 支持 Properties 和 YAML 两种配置格式,通过 Profile 实现多环境配置。配置属性可以通过 @Value 或 @ConfigurationProperties 绑定到 Java 对象。
面试题预览
常见面试题
- Spring Boot 配置文件的加载优先级是怎样的?
- 如何实现多环境配置?
- @Value 和 @ConfigurationProperties 有什么区别?
