Spring Boot application.properties和application.yml文件的配置

在Spring Boot中,`application.properties` 和 `application.yml` 文件用于配置应用程序的各个方面,如服务器端口、数据库连接、日志级别等。这两个文件是Spring Boot的配置文件,位于 `src/main/resources` 目录下。

application.properties 示例

`application.properties` 文件使用键值对的格式进行配置:

复制代码
# 设置服务器端口
server.port=8080
# 数据库配置
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=myuser
spring.datasource.password=mypassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 日志配置
logging.level.root=INFO
logging.level.org.springframework.web=DEBUG
logging.level.org.hibernate=ERROR
# Thymeleaf 配置
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.cache=false

application.yml 示例

`application.yml` 文件使用 YAML(Yet Another Markup Language)格式,它是一种直观的能够被电脑读取的数据序列化格式,并且易于人类阅读。它是JSON的一个超集。

复制代码
# 设置服务器端口
server:
  port: 8080
# 数据库配置
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mydb
    username: myuser
    password: mypassword
    driver-class-name: com.mysql.cj.jdbc.Driver
# 日志配置
logging:
  level:
    root: INFO
    org.springframework.web: DEBUG
    org.hibernate: ERROR
# Thymeleaf 配置
thymeleaf:
  prefix: classpath:/templates/
  suffix: .html
  mode: HTML
  encoding: UTF-8
  cache: false

在 `application.yml` 文件中,可以使用缩进来表示层级关系,使得配置更加清晰。

注意事项

  • `application.properties` 和 `application.yml` 可以同时存在,但是 `application.properties` 中的配置会覆盖 `application.yml` 中的同名配置。

  • `application.yml` 支持数组或列表的配置,例如:`myprops: [~, ~]`。

  • 在 `application.yml` 中,冒号 `:` 后面必须有一个空格。

  • `application.yml` 支持多文档块,可以在同一个文件中分隔多个配置文档。

选择 `application.properties` 还是 `application.yml` 主要取决于个人喜好和项目需求。YAML格式在处理复杂配置时可能更加直观和易于管理。

相关推荐
ssshooter5 分钟前
Tauri 2 iOS 开发避坑指南:文件保存、Dialog 和 Documents 目录的那些坑
前端·后端·ios
追逐时光者19 分钟前
一个基于 .NET Core + Vue3 构建的开源全栈平台 Admin 系统
后端·.net
程序员飞哥24 分钟前
90后大龄程序员失业4个月终于上岸了
后端·面试·程序员
zs宝来了1 小时前
Playwright 自动发布 CSDN 的完整实践
java
彭于晏Yan2 小时前
Redisson分布式锁
spring boot·redis·分布式
吴声子夜歌2 小时前
TypeScript——基础类型(三)
java·linux·typescript
GetcharZp2 小时前
Git 命令行太痛苦?这款 75k Star 的神级工具,让你告别“合并冲突”恐惧症!
后端
Victor3563 小时前
MongoDB(69)如何进行增量备份?
后端
Victor3563 小时前
MongoDB(70)如何使用副本集进行备份?
后端