当前位置: 首页 > news >正文

Spring Boot 配置文件

Spring Boot 配置文件详解

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

1. 配置文件类型

主要配置文件

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

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

  1. 当前目录的 /config 子目录
  2. 当前目录
  3. classpath 的 /config
  4. 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 配置加载顺序(从高到低):

  1. 命令行参数
  2. 来自 java:comp/env 的 JNDI 属性
  3. Java 系统属性 (System.getProperties())
  4. 操作系统环境变量
  5. 打包在 jar 外的配置文件
  6. 打包在 jar 内的配置文件
  7. @PropertySource 注解
  8. 默认属性
http://www.dtcms.com/a/458217.html

相关文章:

  • 批量安装、卸载apk脚本
  • 加盟型网站制作番禺区网站建设公司
  • 视频网站的建设wordpress 模板吧
  • soapUI设置挡板,在mockaction中编写脚本实现根据请求参数的不同来返回不同的响应
  • 什么软件做网站描述排名优化网站
  • 宿城区建设局网站a站是指哪个网站
  • 十大营销网站一女被多男做的视频网站
  • 在使用Nacos作为注册中心和配置中心时,如何解决服务发现延迟或配置更新不及时的问题
  • 站长工具seo推广秒收录禹城网站制作
  • 吾日三省吾身 | 第三季度反思及展望
  • 时间序列预测的相关资源(论文、代码、数据集)
  • vs2013 网站开发怎么区分模板网站
  • 网站建设张景鹏黄骅市天气预报15天气
  • 北京网站建设北京株洲企业关键词优化最新报价
  • Day16_通信总线
  • 如何在 User space 確保全數啟用 PIE CFLAG ?
  • 阿克苏交通建设局网站怎么把在EXCEL做的查询系统做到网站上
  • 深度学习基础:从原理到实践——附录A:PyTorch 深度学习框架基础(上)
  • 外贸网站谷歌seo营销网络搭建
  • 制作网站代码大全有专门做特产的网站吗
  • 深圳网站外包公司简介工业产品外观设计公司
  • 做电商网站都需要学什么软件wordpress搜索功能调用
  • wordpress网站采集插件建一家网站多少钱
  • 视觉手势识别发展历史
  • 单页网站seo网站开发是在电脑上打出来的资料么
  • 百色建设局网站有哪些网站做的好处
  • 全面详解 PyTorch 中的优化器
  • npm 扩展vite、element-plus
  • 好看的网站首页特效网页设计作品简单
  • dedecms织梦古典艺术书画书法公司企业网站源码模板网页设计茶叶网站建设