SpringBoot3.x入门到精通系列:1.5 配置文件详解
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-appprofiles:active: dev# 服务器配置
server:port: 8080servlet:context-path: /apiencoding:charset: UTF-8enabled: trueforce: true
2. 数据库配置
spring:# 数据源配置datasource:url: jdbc:mysql://localhost:3306/demo_db?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghaiusername: rootpassword: 123456driver-class-name: com.mysql.cj.jdbc.Driver# HikariCP连接池配置hikari:maximum-pool-size: 20minimum-idle: 5idle-timeout: 300000connection-timeout: 20000max-lifetime: 1200000pool-name: HikariCP# JPA配置jpa:hibernate:ddl-auto: updateshow-sql: trueopen-in-view: falseproperties:hibernate:format_sql: truedialect: org.hibernate.dialect.MySQL8Dialect# Redis配置data:redis:host: localhostport: 6379password: database: 0timeout: 2000mslettuce:pool:max-active: 8max-idle: 8min-idle: 0max-wait: -1ms
3. 完整的生产环境配置
spring:application:name: demo-appprofiles: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.Driverhikari:maximum-pool-size: 50minimum-idle: 10idle-timeout: 600000connection-timeout: 30000max-lifetime: 1800000# JPA配置jpa:hibernate:ddl-auto: validateshow-sql: falseopen-in-view: false# 缓存配置cache:type: redisredis:time-to-live: 600000# 安全配置security:user:name: adminpassword: ${ADMIN_PASSWORD:admin123}# 服务器配置
server:port: ${SERVER_PORT:8080}servlet:context-path: /apicompression:enabled: truemime-types: text/html,text/xml,text/plain,text/css,text/javascript,application/javascript,application/jsonmin-response-size: 1024# 管理端点配置
management:endpoints:web:exposure:include: health,info,metrics,prometheusendpoint:health:show-details: when-authorizedmetrics:export:prometheus:enabled: true# 日志配置
logging:level:root: WARNcom.example.demo: INFOorg.springframework.security: DEBUGfile:name: logs/application.logmax-size: 50MBmax-history: 30pattern: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:testdbdriver-class-name: org.h2.Driverusername: sapassword: h2:console:enabled: truepath: /h2-consolejpa:hibernate:ddl-auto: create-dropshow-sql: truelogging:level:com.example.demo: DEBUGorg.springframework.web: DEBUGserver:port: 8080
3. 生产环境配置 (application-prod.yml)
spring:datasource:url: ${DB_URL}username: ${DB_USERNAME}password: ${DB_PASSWORD}hikari:maximum-pool-size: 50jpa:hibernate:ddl-auto: validateshow-sql: falselogging:level:root: WARNcom.example.demo: INFOfile:name: /var/log/demo-app/application.logserver: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 Applicationversion: 1.0.0security:enabled: truesecret-key: ${SECRET_KEY:mySecretKey123}token-expiration: 7200database:max-connections: 50timeout: 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 {@NotBlankprivate String name;@Min(1)@Max(65535)private int port;@Validprivate Database database;public static class Database {@NotBlankprivate String url;@Min(1)private int maxConnections;}
}
🔗 下一篇
在下一篇文章中,我们将深入学习SpringBoot的自动配置原理,了解SpringBoot是如何实现"开箱即用"的。
本文关键词: 配置文件, application.yml, 多环境配置, ConfigurationProperties, 配置优先级