SpringBoot之配置文件
大纲:什么是配置文件,有哪些格式,配置文件的主要内容(各种类型),常用配置有哪些,优先顺序是什么,怎么读取配置文件中的内容,多环境配置。
一、配置文件概述
Springboot配置文件是一个文本文件,分为properties和yaml格式,内部设置了项目启动的一系列参数,比如:端口号、应用名称、激活的配置环境等。该文件体现来SpringBoot的“约定大于配置”的思想。
二、配置文件核心知识
2.1 分类
分为properties和yaml/yml两类,properties的优先级高于yaml/yml,当出现配置冲突时,properties会覆盖yaml/yml中的冲突项。
2.2 数据格式
2.2.1 properties文件
该文件的内容形式为传统键值对,key=value
样例:
# 字符串配置
app.name=MySpringBootApp
app.description=This is a Spring Boot application# 数字配置
server.port=8080
database.connection.timeout=30000# 布尔值配置
feature.enabled=true
security.ssl=false# 对象配置(通过层级键名表示)
person.name=John Doe
person.age=30
person.address.city=Beijing
person.address.zipcode=100000# 列表/数组配置
user.roles[0]=ADMIN
user.roles[1]=USER
user.hobbies=Reading,Swimming,Coding# Map配置
app.settings.key1=value1
app.settings.key2=value2# 多行字符串(使用反斜杠)
welcome.message=Welcome to our application.\This is a multi-line message.\Thank you for choosing us.# 日期配置
app.release.date=2023/01/06# null值配置
temp.value=null# 空字符串
temp.value2=
temp.value3=""
2.2.2 yaml/yml文件
# 字符串配置
app:name: MySpringBootAppdescription: This is a Spring Boot application# 数字配置
server:port: 8080
database:connection:timeout: 30000# 布尔值配置
feature:enabled: true
security:ssl: false# 对象配置
person:name: John Doeage: 30address:city: Beijingzipcode: "100000"# 列表/数组配置
user:roles:- ADMIN- USERhobbies:- Reading- Swimming- Coding# Map配置
app:settings:key1: value1key2: value2# 行内写法(简洁格式)
inline:person: {name: John, age: 30}hobbies: [Reading, Swimming, Coding]# 多行字符串
welcome:message: |Welcome to our application.This is a multi-line message.Thank you for choosing us.# 日期配置
app:release-date: 2023/01/06# null值配置
temp:value: null# 复杂嵌套结构(对象中包含数组)
departments:- name: Engineeringemployees:- {name: Alice, age: 28, role: Developer}- {name: Bob, age: 32, role: Architect}projects: [ProjectA, ProjectB]- name: Marketingemployees:- {name: Carol, age: 25, role: Manager}projects: [CampaignX]
2.3 常用配置项
# 应用基本信息
spring.application.name=my-springboot-app
# 激活的环境配置(dev, test, prod)
spring.profiles.active=dev
# 是否开启调试模式
debug=false# 服务器配置
# 服务器端口号
server.port=8080
# 应用上下文路径(访问根路径)
server.servlet.context-path=/
# 服务器绑定地址(默认所有网卡)
server.address=0.0.0.0
# 会话超时时间(秒)
server.servlet.session.timeout=1800
# 文件上传最大大小
spring.servlet.multipart.max-file-size=10MB
# 单次请求最大文件总大小
spring.servlet.multipart.max-request-size=50MB# Tomcat 特定配置(如果使用Tomcat)
# 最大工作线程数
server.tomcat.max-threads=200
# URI 编码
server.tomcat.uri-encoding=UTF-8# 数据源配置
# 数据库连接URL
spring.datasource.url=jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=Asia/Shanghai
# 数据库驱动类名
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 数据库用户名
spring.datasource.username=root
# 数据库密码
spring.datasource.password=123456
# HikariCP 连接池配置(Spring Boot 默认)
# 连接超时时间(毫秒)
spring.datasource.hikari.connection-timeout=30000
# 最大连接数
spring.datasource.hikari.maximum-pool-size=20
# 最小空闲连接数
spring.datasource.hikari.minimum-idle=5
# 连接最大存活时间(毫秒)
spring.datasource.hikari.max-lifetime=1800000# JPA & Hibernate 配置
# DDL自动生成策略(none/update/create/create-drop)
spring.jpa.hibernate.ddl-auto=update
# 是否在控制台显示SQL
spring.jpa.show-sql=true
# 是否格式化显示的SQL
spring.jpa.properties.hibernate.format_sql=true
# 设置Hibernate方言
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
# 日志配置
# 根日志级别(trace/debug/info/warn/error)
logging.level.root=info
# 指定包下的日志级别
logging.level.com.yourpackage=debug
# 日志文件名称
logging.file.name=app.log
# 日志文件存储路径
logging.file.path=./logs
# 控制台日志输出格式
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} - %msg%n
# 文件日志输出格式
logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
# 缓存配置
# 缓存类型(simple, caffeine, redis, ehcache)
spring.cache.type=caffeine# Caffeine(本地缓存)专用配置
# 缓存策略:最大容量500,写入10分钟后过期
spring.cache.caffeine.spec=maximumSize=500,expireAfterWrite=10m# Redis(分布式缓存)专用配置
# Redis服务器地址
spring.redis.host=localhost
# Redis端口
spring.redis.port=6379
# Redis密码(如果没有密码则注释掉)
# spring.redis.password=yourpassword
# 连接超时时间(毫秒)
spring.redis.timeout=3000
# Spring Security 基础配置
# 内存认证的用户名(简单场景)
spring.security.user.name=admin
# 内存认证的密码
spring.security.user.password=admin123
# 是否启用CSRF保护(API场景可关闭)
spring.security.csrf.enabled=true
# RabbitMQ 配置
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest# Kafka 配置
spring.kafka.bootstrap-servers=localhost:9092
spring.kafka.consumer.group-id=my-group# 邮件配置
spring.mail.host=smtp.qq.com
spring.mail.port=587
spring.mail.username=your-email@qq.com
spring.mail.password=your-authorization-code
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
# Actuator 监控端点配置
# 暴露的HTTP端点(health, info, metrics等)
management.endpoints.web.exposure.include=health,info,metrics
# 健康检查详情显示规则
management.endpoint.health.show-details=when_authorized
# 应用信息自定义(在/info端点显示)
info.app.name=@spring.application.name@
info.app.version=1.0.0
2.4 配置文件加载顺序
先加载的配置文件优先级更高,同位置下,approperties文件优先级高于yaml文件。加载顺序如下:
1、命令行参数(如--server.port=9000
)
2、操作系统环境变量
3、当前项目根目录下的/config
子目录中的配置文件
4、当前项目的根目录下的配置文件
5、类路径(classpath)下的/config
目录中的配置文件
6、类路径(classpath)根目录下的默认配置文件
2.5 读取配置项
方法 | 示例 |
@Value |
|
@ConfigurationProperties |
|
Environment |
|
@PropertySource |
|
2.6 多环境激活
命令行参数,用于生产环境:
java -jar your-app.jar --spring.profiles.active=prod
JVM 系统参数:在 IDE 的运行时配置或服务器启动脚本中设置。
-Dspring.profiles.active=dev
配置文件指定 (最低优先级):在主配置文件 application.yml中设置默认激活的环境,通常用于开发阶段。
spring.profiles.active=dev