SpringBoot 3.x 配置文件详解
📋 配置文件概述
SpringBoot支持多种配置文件格式,按优先级排序:
- application.properties - 传统的键值对格式
- application.yml/yaml - YAML格式,层次结构清晰
- application.json - JSON格式(较少使用)
🔧 application.properties详解
1. 基本配置
# 应用基本信息
spring.application.name=demo-app
server.port=8080
server.servlet.context-path=/api
# 环境配置
spring.profiles.active=dev
# 字符编码
server.servlet.encoding.charset=UTF-8
server.servlet.encoding.enabled=true
server.servlet.encoding.force=true
2. 数据库配置
# 数据源配置
spring.datasource.url=jdbc:mysql://localhost:3306/demo_db?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 连接池配置
spring.datasource.hikari.maximum-pool-size=20
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.idle-timeout=300000
spring.datasource.hikari.connection-timeout=20000
spring.datasource.hikari.max-lifetime=1200000
# JPA配置
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
spring.jpa.open-in-view=false
3. Redis配置
# Redis配置
spring.data.redis.host=localhost
spring.data.redis.port=6379
spring.data.redis.password=
spring.data.redis.database=0
spring.data.redis.timeout=2000ms
# Redis连接池配置
spring.data.redis.lettuce.pool.max-active=8
spring.data.redis.lettuce.pool.max-idle=8
spring.data.redis.lettuce.pool.min-idle=0
spring.data.redis.lettuce.pool.max-wait=-1ms
4. 日志配置
# 日志级别配置
logging.level.root=INFO
logging.level.com.example.demo=DEBUG
logging.level.org.springframework.web=DEBUG
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
# 日志文件配置
logging.file.name=logs/application.log
logging.file.max-size=10MB
logging.file.max-history=30
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
📄 application.yml详解
1. 基本配置
# 应用配置
spring:
application:
name: demo-app
profiles:
active: dev
# 服务器配置
server:
port: 8080
servlet:
context-path: /api
encoding:
charset: UTF-8
enabled: true
force: true
2. 数据库配置
spring:
# 数据源配置
datasource:
url: jdbc:mysql://localhost:3306/demo_db?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
# HikariCP连接池配置
hikari:
maximum-pool-size: 20
minimum-idle: 5
idle-timeout: 300000
connection-timeout: 20000
max-lifetime: 1200000
pool-name: HikariCP
# JPA配置
jpa:
hibernate:
ddl-auto: update
show-sql: true
open-in-view: false
properties:
hibernate:
format_sql: true
dialect: org.hibernate.dialect.MySQL8Dialect
# Redis配置
data:
redis:
host: localhost
port: 6379
password:
database: 0
timeout: 2000ms
lettuce:
pool:
max-active: 8
max-idle: 8
min-idle: 0
max-wait: -1ms
3. 完整的生产环境配置
spring:
application:
name: demo-app
profiles:
active: prod
# 数据源配置
datasource:
url: ${DB_URL:jdbc:mysql://localhost:3306/demo_db}
username: ${DB_USERNAME:root}
password: ${DB_PASSWORD:123456}
driver-class-name: com.mysql.cj.jdbc.Driver
hikari:
maximum-pool-size: 50
minimum-idle: 10
idle-timeout: 600000
connection-timeout: 30000
max-lifetime: 1800000
# JPA配置
jpa:
hibernate:
ddl-auto: validate
show-sql: false
open-in-view: false
# 缓存配置
cache:
type: redis
redis:
time-to-live: 600000
# 安全配置
security:
user:
name: admin
password: ${ADMIN_PASSWORD:admin123}
# 服务器配置
server:
port: ${SERVER_PORT:8080}
servlet:
context-path: /api
compression:
enabled: true
mime-types: text/html,text/xml,text/plain,text/css,text/javascript,application/javascript,application/json
min-response-size: 1024
# 管理端点配置
management:
endpoints:
web:
exposure:
include: health,info,metrics,prometheus
endpoint:
health:
show-details: when-authorized
metrics:
export:
prometheus:
enabled: true
# 日志配置
logging:
level:
root: WARN
com.example.demo: INFO
org.springframework.security: DEBUG
file:
name: logs/application.log
max-size: 50MB
max-history: 30
pattern:
console: "%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n"
file: "%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n"
🌍 多环境配置
1. 配置文件命名规则
application.properties # 默认配置
application-dev.properties # 开发环境
application-test.properties # 测试环境
application-prod.properties # 生产环境
2. 开发环境配置 (application-dev.yml)
spring:
datasource:
url: jdbc:h2:mem:testdb
driver-class-name: org.h2.Driver
username: sa
password:
h2:
console:
enabled: true
path: /h2-console
jpa:
hibernate:
ddl-auto: create-drop
show-sql: true
logging:
level:
com.example.demo: DEBUG
org.springframework.web: DEBUG
server:
port: 8080
3. 生产环境配置 (application-prod.yml)
spring:
datasource:
url: ${DB_URL}
username: ${DB_USERNAME}
password: ${DB_PASSWORD}
hikari:
maximum-pool-size: 50
jpa:
hibernate:
ddl-auto: validate
show-sql: false
logging:
level:
root: WARN
com.example.demo: INFO
file:
name: /var/log/demo-app/application.log
server:
port: ${PORT:8080}
management:
endpoints:
web:
exposure:
include: health,metrics
🔐 自定义配置属性
1. 使用@ConfigurationProperties
package com.example.demo.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "app")
public class AppProperties {
private String name;
private String version;
private Security security = new Security();
private Database database = new Database();
// Getter和Setter方法
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getVersion() { return version; }
public void setVersion(String version) { this.version = version; }
public Security getSecurity() { return security; }
public void setSecurity(Security security) { this.security = security; }
public Database getDatabase() { return database; }
public void setDatabase(Database database) { this.database = database; }
// 内部类
public static class Security {
private boolean enabled = true;
private String secretKey;
private int tokenExpiration = 3600;
// Getter和Setter方法
public boolean isEnabled() { return enabled; }
public void setEnabled(boolean enabled) { this.enabled = enabled; }
public String getSecretKey() { return secretKey; }
public void setSecretKey(String secretKey) { this.secretKey = secretKey; }
public int getTokenExpiration() { return tokenExpiration; }
public void setTokenExpiration(int tokenExpiration) { this.tokenExpiration = tokenExpiration; }
}
public static class Database {
private int maxConnections = 20;
private int timeout = 30000;
// Getter和Setter方法
public int getMaxConnections() { return maxConnections; }
public void setMaxConnections(int maxConnections) { this.maxConnections = maxConnections; }
public int getTimeout() { return timeout; }
public void setTimeout(int timeout) { this.timeout = timeout; }
}
}
2. 对应的配置文件
app:
name: Demo Application
version: 1.0.0
security:
enabled: true
secret-key: ${SECRET_KEY:mySecretKey123}
token-expiration: 7200
database:
max-connections: 50
timeout: 60000
3. 使用Record简化配置类 (Java 17+)
package com.example.demo.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "app")
public record AppProperties(
String name,
String version,
Security security,
Database database
) {
public record Security(
boolean enabled,
String secretKey,
int tokenExpiration
) {}
public record Database(
int maxConnections,
int timeout
) {}
}
4. 在业务代码中使用
@Service
public class UserService {
private final AppProperties appProperties;
public UserService(AppProperties appProperties) {
this.appProperties = appProperties;
}
public void someMethod() {
if (appProperties.getSecurity().isEnabled()) {
// 安全相关逻辑
String secretKey = appProperties.getSecurity().getSecretKey();
int expiration = appProperties.getSecurity().getTokenExpiration();
}
int maxConnections = appProperties.getDatabase().getMaxConnections();
// 数据库相关逻辑
}
}
🔄 配置文件优先级
SpringBoot配置文件的加载优先级(从高到低):
- 命令行参数
- 系统环境变量
application-{profile}.properties/yml
application.properties/yml
@PropertySource
注解指定的配置文件- 默认配置
示例:覆盖配置
# 命令行参数(最高优先级)
java -jar app.jar --server.port=9090 --spring.profiles.active=prod
# 环境变量
export SERVER_PORT=8081
export SPRING_PROFILES_ACTIVE=dev
📊 配置最佳实践
1. 敏感信息处理
# 使用环境变量
spring:
datasource:
password: ${DB_PASSWORD:defaultPassword}
# 使用配置服务器
spring:
cloud:
config:
uri: http://config-server:8888
2. 配置验证
@ConfigurationProperties(prefix = "app")
@Validated
public class AppProperties {
@NotBlank
private String name;
@Min(1)
@Max(65535)
private int port;
@Valid
private Database database;
public static class Database {
@NotBlank
private String url;
@Min(1)
private int maxConnections;
}
}
🔗 下一篇
在下一篇文章中,我们将深入学习SpringBoot的自动配置原理,了解SpringBoot是如何实现"开箱即用"的。
本文关键词: 配置文件, application.yml, 多环境配置, ConfigurationProperties, 配置优先级