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

相关推荐
万少3 小时前
用腻了 WorkBuddy 的默认界面?这个开源小工具给它换上了毛玻璃
前端·javascript·后端
皮皮林5515 小时前
代码越“整洁”,性能越“拉胯”?
后端
金金金__6 小时前
一篇文章带你入门OpenSpec
后端
阿维的博客日记7 小时前
MultipartFile 是不是表示仅仅是一个分片?
java·后端·spring·multipartfile
海上彼尚7 小时前
Nodejs也能写Agent - 16.LangGraph篇 - 条件分支与循环
前端·后端·langchain·node.js
程序员无隅7 小时前
Coding Agent 为什么压缩上下文后还能继续工作?上下文模块设计拆解
java·开发语言·数据库
Python+997 小时前
Java 枚举类(Enum)详解:从基础到高级应用
java·开发语言·python
二炮手亮子7 小时前
浅记java线程池
java·开发语言
一路向北North7 小时前
Spring Security OAuth2.0(23):分布式系统授权-转发明文给微服务
java·spring·微服务
Dovis(誓平步青云)8 小时前
远程办公软件文件传输实测:6 款工具的速度、稳定性和办公体验对比
linux·运维·服务器·后端·生成对抗网络