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. 默认属性
相关推荐
lkbhua莱克瓦2414 分钟前
多线程综合练习3
java·开发语言·多线程·githup
摸鱼仙人~15 分钟前
企业级 RAG 问答系统开发上线流程分析
后端·python·rag·检索
步步为营DotNet27 分钟前
深度解析.NET中属性(Property)的幕后机制:优化数据访问与封装
java·算法·.net
Swift社区27 分钟前
LeetCode 454 - 四数相加 II
java·算法·leetcode
想做后端的小C28 分钟前
Java:访问权限
java·开发语言
啃火龙果的兔子29 分钟前
java语言基础
java·开发语言·python
我命由我1234531 分钟前
Python 开发问题:No Python interpreter configured for the project
开发语言·后端·python·学习·pycharm·学习方法·python3.11
禾高网络32 分钟前
互联网医院定制|互联网医院|禾高互联网医院搭建
java·大数据·人工智能·小程序
伏加特遇上西柚34 分钟前
集成健康探测以及服务优雅下线接口
spring boot
掘根35 分钟前
【消息队列项目】消费者管理模块实现
java·开发语言