Spring Boot 配置文件
Spring Boot 配置文件详解
Spring Boot 提供了强大的配置文件系统,支持多种配置方式和灵活的配置管理。
1. 配置文件类型
主要配置文件:
application.properties
(最常用)application.yml
/application.yaml
(推荐)
位置优先级(从高到低):
- 当前目录的
/config
子目录 - 当前目录
- classpath 的
/config
包 - classpath 根目录
2. 基础配置示例
application.properties:
# 服务器配置
server.port=8080
server.servlet.context-path=/panda-wiki# 应用配置
spring.application.name=panda-wiki# 数据库配置
spring.datasource.url=jdbc:mysql://localhost:3306/wiki
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver# JPA配置
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect# 日志配置
logging.level.com.panda.wiki=DEBUG
logging.file.name=logs/panda-wiki.log
application.yml:
# 服务器配置
server:port: 8080servlet:context-path: /panda-wiki# 应用配置
spring:application:name: panda-wiki# 数据库配置datasource:url: jdbc:mysql://localhost:3306/wikiusername: rootpassword: 123456driver-class-name: com.mysql.cj.jdbc.Driver# JPA配置jpa:hibernate:ddl-auto: updateshow-sql: trueproperties:hibernate:dialect: org.hibernate.dialect.MySQL8Dialect# 日志配置
logging:level:com.panda.wiki: DEBUGfile:name: logs/panda-wiki.log
3. 多环境配置
环境特定配置文件:
application-dev.properties
- 开发环境application-test.properties
- 测试环境application-prod.properties
- 生产环境
激活特定环境:
方法1:主配置文件中指定
# application.properties
spring.profiles.active=dev
方法2:启动参数指定
java -jar panda-wiki.jar --spring.profiles.active=prod
方法3:环境变量指定
export SPRING_PROFILES_ACTIVE=test
环境配置示例:
开发环境 (application-dev.properties
):
# 开发环境配置
server.port=8080
spring.datasource.url=jdbc:h2:mem:testdb
spring.jpa.show-sql=true
logging.level.com.panda.wiki=DEBUG
生产环境 (application-prod.properties
):
# 生产环境配置
server.port=80
spring.datasource.url=jdbc:mysql://prod-db:3306/wiki
spring.jpa.show-sql=false
logging.level.com.panda.wiki=WARN
management.endpoints.web.exposure.include=health,info
4. YAML 多文档配置
在单个 YAML 文件中配置多环境:
# 通用配置
spring:application:name: panda-wiki
logging:level:root: WARN---
# 开发环境
spring:config:activate:on-profile: devdatasource:url: jdbc:h2:mem:testdb
server:port: 8080---
# 生产环境
spring:config:activate:on-profile: proddatasource:url: jdbc:mysql://prod-server:3306/wiki
server:port: 80
5. 配置注入方式
使用 @Value 注解:
@Component
public class AppConfig {@Value("${server.port}")private int serverPort;@Value("${spring.application.name}")private String appName;@Value("${app.feature.enabled:false}") // 默认值private boolean featureEnabled;
}
使用 @ConfigurationProperties(推荐):
@Configuration
@ConfigurationProperties(prefix = "app")
public class AppProperties {private String name;private String version;private Security security = new Security();// getters and setterspublic static class Security {private boolean enabled;private String secretKey;// getters and setters}
}// 在 application.properties 中:
app.name=PandaWiki
app.version=1.0.0
app.security.enabled=true
app.security.secret-key=my-secret-key
6. 常用配置分类
Web 相关配置:
# 服务器
server.port=8080
server.servlet.context-path=/api# Tomcat 配置
server.tomcat.max-threads=200
server.tomcat.max-connections=10000# 文件上传
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
数据库相关配置:
# 数据源
spring.datasource.url=jdbc:mysql://localhost:3306/wiki
spring.datasource.username=root
spring.datasource.password=123456# 连接池 (HikariCP)
spring.datasource.hikari.maximum-pool-size=20
spring.datasource.hikari.minimum-idle=5# JPA
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.open-in-view=false
安全相关配置:
# JWT
jwt.secret=mySecretKey
jwt.expiration=86400000# 加密
bcrypt.strength=10
缓存配置:
# Redis
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=# 缓存配置
spring.cache.type=redis
spring.cache.redis.time-to-live=3600000
7. 高级配置特性
配置占位符:
app.name=PandaWiki
app.version=1.0.0
app.description=${app.name} version ${app.version}
环境变量引用:
# 使用环境变量
spring.datasource.url=${DATABASE_URL:jdbc:h2:mem:testdb}
spring.datasource.username=${DB_USERNAME:root}
spring.datasource.password=${DB_PASSWORD:}# 命令行参数
server.port=${PORT:8080}
随机值配置:
# 随机值
app.secret=${random.value}
app.number=${random.int}
app.bignumber=${random.long}
app.uuid=${random.uuid}
app.range=${random.int[100,200]}
8. 自定义配置文件
创建自定义配置文件:
# custom.properties
app.upload.dir=uploads
app.max-file-size=10MB
app.allowed-file-types=jpg,png,pdf
加载自定义配置:
@Configuration
@PropertySource("classpath:custom.properties")
public class CustomConfig {@Value("${app.upload.dir}")private String uploadDir;
}
9. 配置验证
使用 @Validated:
@Configuration
@ConfigurationProperties(prefix = "app")
@Validated
public class AppProperties {@NotNullprivate String name;@Min(1)@Max(100)private int maxUsers;// getters and setters
}
10. 最佳实践
配置组织建议:
src/main/resources/
├── application.yml # 通用配置
├── application-dev.yml # 开发环境
├── application-test.yml # 测试环境
├── application-prod.yml # 生产环境
└── application-local.yml # 本地开发
安全配置建议:
- 敏感信息(密码、密钥)使用环境变量
- 生产环境配置单独管理
- 使用配置服务器(Spring Cloud Config)集中管理
调试配置:
# 查看所有配置
debug=true# 查看自动配置报告
logging.level.org.springframework.boot.autoconfigure=DEBUG
11. 配置优先级总结
Spring Boot 配置加载顺序(从高到低):
- 命令行参数
- 来自
java:comp/env
的 JNDI 属性 - Java 系统属性 (
System.getProperties()
) - 操作系统环境变量
- 打包在 jar 外的配置文件
- 打包在 jar 内的配置文件
@PropertySource
注解- 默认属性