Spring Boot 配置文件

Spring Boot 配置文件详解

Spring Boot 提供了强大的配置文件系统,支持多种配置方式和灵活的配置管理。

1. 配置文件类型

主要配置文件

  • application.properties (最常用)
  • application.yml / application.yaml (推荐)

位置优先级(从高到低):

  1. 当前目录的 /config 子目录
  2. 当前目录
  3. classpath 的 /config
  4. classpath 根目录

2. 基础配置示例

application.properties

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

yaml 复制代码
# 服务器配置
server:
  port: 8080
  servlet:
    context-path: /panda-wiki

# 应用配置
spring:
  application:
    name: panda-wiki
  
  # 数据库配置
  datasource:
    url: jdbc:mysql://localhost:3306/wiki
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
  
  # JPA配置
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
    properties:
      hibernate:
        dialect: org.hibernate.dialect.MySQL8Dialect

# 日志配置
logging:
  level:
    com.panda.wiki: DEBUG
  file:
    name: logs/panda-wiki.log

3. 多环境配置

环境特定配置文件

  • application-dev.properties - 开发环境
  • application-test.properties - 测试环境
  • application-prod.properties - 生产环境

激活特定环境

方法1:主配置文件中指定
properties 复制代码
# application.properties
spring.profiles.active=dev
方法2:启动参数指定
bash 复制代码
java -jar panda-wiki.jar --spring.profiles.active=prod
方法3:环境变量指定
bash 复制代码
export SPRING_PROFILES_ACTIVE=test

环境配置示例

开发环境 (application-dev.properties):
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):
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 文件中配置多环境:

yaml 复制代码
# 通用配置
spring:
  application:
    name: panda-wiki
logging:
  level:
    root: WARN

---
# 开发环境
spring:
  config:
    activate:
      on-profile: dev
  datasource:
    url: jdbc:h2:mem:testdb
server:
  port: 8080

---
# 生产环境  
spring:
  config:
    activate:
      on-profile: prod
  datasource:
    url: jdbc:mysql://prod-server:3306/wiki
server:
  port: 80

5. 配置注入方式

使用 @Value 注解

java 复制代码
@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(推荐):

java 复制代码
@Configuration
@ConfigurationProperties(prefix = "app")
public class AppProperties {
    private String name;
    private String version;
    private Security security = new Security();
    
    // getters and setters
    
    public 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 相关配置

properties 复制代码
# 服务器
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

数据库相关配置

properties 复制代码
# 数据源
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

安全相关配置

properties 复制代码
# JWT
jwt.secret=mySecretKey
jwt.expiration=86400000

# 加密
bcrypt.strength=10

缓存配置

properties 复制代码
# Redis
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=

# 缓存配置
spring.cache.type=redis
spring.cache.redis.time-to-live=3600000

7. 高级配置特性

配置占位符

properties 复制代码
app.name=PandaWiki
app.version=1.0.0
app.description=${app.name} version ${app.version}

环境变量引用

properties 复制代码
# 使用环境变量
spring.datasource.url=${DATABASE_URL:jdbc:h2:mem:testdb}
spring.datasource.username=${DB_USERNAME:root}
spring.datasource.password=${DB_PASSWORD:}

# 命令行参数
server.port=${PORT:8080}

随机值配置

properties 复制代码
# 随机值
app.secret=${random.value}
app.number=${random.int}
app.bignumber=${random.long}
app.uuid=${random.uuid}
app.range=${random.int[100,200]}

8. 自定义配置文件

创建自定义配置文件

properties 复制代码
# custom.properties
app.upload.dir=uploads
app.max-file-size=10MB
app.allowed-file-types=jpg,png,pdf

加载自定义配置

java 复制代码
@Configuration
@PropertySource("classpath:custom.properties")
public class CustomConfig {
    
    @Value("${app.upload.dir}")
    private String uploadDir;
}

9. 配置验证

使用 @Validated

java 复制代码
@Configuration
@ConfigurationProperties(prefix = "app")
@Validated
public class AppProperties {
    
    @NotNull
    private String name;
    
    @Min(1)
    @Max(100)
    private int maxUsers;
    
    // getters and setters
}

10. 最佳实践

配置组织建议

bash 复制代码
src/main/resources/
├── application.yml           # 通用配置
├── application-dev.yml       # 开发环境
├── application-test.yml      # 测试环境
├── application-prod.yml      # 生产环境
└── application-local.yml     # 本地开发

安全配置建议

  • 敏感信息(密码、密钥)使用环境变量
  • 生产环境配置单独管理
  • 使用配置服务器(Spring Cloud Config)集中管理

调试配置

properties 复制代码
# 查看所有配置
debug=true

# 查看自动配置报告
logging.level.org.springframework.boot.autoconfigure=DEBUG

11. 配置优先级总结

Spring Boot 配置加载顺序(从高到低):

  1. 命令行参数
  2. 来自 java:comp/env 的 JNDI 属性
  3. Java 系统属性 (System.getProperties())
  4. 操作系统环境变量
  5. 打包在 jar 外的配置文件
  6. 打包在 jar 内的配置文件
  7. @PropertySource 注解
  8. 默认属性
相关推荐
IT_Octopus2 小时前
https私人证书 PKIX path building failed 报错解决
java·spring boot·网络协议·https
绝无仅有2 小时前
远景集团面试后端Java岗位问答与总结汇总
后端·面试·github
欧阳码农2 小时前
忍了一年多,我做了一个工具将文章一键发布到多个平台
前端·人工智能·后端
程序员清风2 小时前
网易三面:Java中默认使用的垃圾回收器及特点分版本说说?
java·后端·面试
hui函数2 小时前
Python全栈(基础篇)——Day07:后端内容(函数的参数+递归函数+实战演示+每日一题)
后端·python
爱吃烤鸡翅的酸菜鱼2 小时前
深度掌握 Git 分支体系:从基础操作到高级策略与实践案例
分布式·git·后端·gitee·github
这周也會开心2 小时前
本地部署javaweb项目到Tomcat的三种方法
java·tomcat
IT_陈寒2 小时前
Python性能优化:5个让你的代码提速300%的NumPy高级技巧
前端·人工智能·后端
风象南2 小时前
从RBAC到ABAC的进阶之路:基于jCasbin实现无侵入的SpringBoot权限校验
spring boot·后端