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格式在处理复杂配置时可能更加直观和易于管理。

相关推荐
勇往直前plus20 小时前
从文件到屏幕:Python/java 字符编码、解码、文本处理的底层逻辑解析
java·开发语言·python
Drifter_yh1 天前
【黑马点评】Redisson 分布式锁核心原理剖析
java·数据库·redis·分布式·spring·缓存
莫寒清1 天前
Spring MVC:@RequestParam 注解详解
java·spring·mvc
没有医保李先生1 天前
字节对齐的总结
java·开发语言
甲枫叶1 天前
【claude】Claude Code正式引入Git Worktree原生支持:Agent全面实现并行独立工作
java·人工智能·git·python·ai编程
六件套是我1 天前
无法访问org.springframeword.beans.factory.annotation.Value
java·开发语言·spring boot
LYS_06181 天前
C++学习(5)(函数 指针 引用)
java·c++·算法
forestsea1 天前
Spring Cloud Alibaba 2025.1.0.0 正式发布:拥抱 Spring Boot 4.0 与 Java 21+ 的新时代
java·spring boot·后端
IT枫斗者1 天前
IntelliJ IDEA 2025.3史诗级更新:统一发行版+Spring Boot 4支持,这更新太香了!
java·开发语言·前端·javascript·spring boot·后端·intellij-idea