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

相关推荐
不能放弃治疗1 小时前
上下文压缩机制
后端
QQ_21696290961 小时前
【项目编号:project95315】SpringBoot公共自习室管理系统:座位预约、房间管理、签到核销、公告规则完整实战
java·spring boot·后端
凤山老林1 小时前
高可用服务容错架构:Spring Boot 集成 Resilience4j 实战指南
spring boot·后端·架构·resilience4j
手握风云-1 小时前
Spring Cloud:分布式系统的“粘合剂”(五)
后端·spring·spring cloud
早点睡9751 小时前
Python 上下文管理器深度剖析:从 with 语法糖到 CPython 底层协议
后端·面试
嵌入式阿蔡1 小时前
面试高频考点 01:volatile / 中断 / 堆栈 八股精讲
java·面试·职场和发展·嵌入式实时数据库
Cache技术分享1 小时前
503. Java 反射 - 编写 ServiceFactory 类
前端·后端
高频因子挖掘机1 小时前
QuantDash 成交量单位统一实战:从“手”到“股”的跨市场量化数据清洗全流程
后端·算法·github
码农看码1 小时前
Spring Boot 启动到响应:一个 HTTP 请求是怎么走到 Controller 的?
后端
秋饼2 小时前
LangChain4j + Java 实现企业级 Text-to-SQL 智能问数系统:从自然语言到安全可控的数据洞察
java·ai·技术分享·后端开发