SpringBoot配置文件详解(配置格式及使用示例)

SpringBoot配置文件详解(配置格式及使用示例)-mikechen

SpringBoot配置文件定义

Spring Boot的配置文件是用于配置Spring Boot应用程序的一种文件,它包含了应用程序的各种配置信息,例如端口号、数据库连接、日志记录器等。

Spring Boot的配置文件可以存储在多个位置,例如classpath下的application.propertiesapplication.yml文件、外部配置文件等。

在Spring Boot应用程序启动时,它会自动读取这些配置文件,将配置信息应用到应用程序中相应的组件中。

 

SpringBoot配置文件格式

Spring Boot支持多种配置文件格式,包括properties和yaml。

1.properties格式

properties文件格式是key=value的形式,一般用于配置简单的属性。

在Spring Boot中,可以通过在application.properties文件中设置属性来配置应用程序。

示例如下:

server.port=8080
spring.datasource.url=jdbc:mysql://localhost:3306/testdb
spring.datasource.username=root
spring.datasource.password=123456

 

2.YAML文件格式

在Spring Boot中,可以通过在application.yml文件中设置属性来配置应用程序。

YAML文件格式是基于缩进的层级结构,相对于properties文件更加灵活和易读。

示例如下:

server:
  port: 8080
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/testdb
    username: root
    password: 123456

在YAML文件中,每个属性都必须对齐,并且不能使用tab键进行缩进。

 

SpringBoot配置文件示例

下面是一个使用application.yml作为配置文件的示例:

# 服务端口号
server:
  port: 8080

# 数据库配置
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC&characterEncoding=utf-8
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver

# MyBatis配置
mybatis:
  mapper-locations: classpath:mapper/*.xml
  configuration:
    map-underscore-to-camel-case: true

# 日志配置
logging:
  level:
    root: info
    com.example: debug

这个配置文件包含了几个常见的配置项:

  • server.port:配置应用程序的服务端口号;
  • spring.datasource:配置应用程序的数据源,包括数据库连接地址、用户名、密码和驱动程序类名;
  • mybatis:配置MyBatis框架的相关选项,例如Mapper文件的位置和数据库字段名和Java属性名之间的映射规则;
  • logging:配置日志记录器的日志级别,例如root logger的日志级别为info,而com.example包下的日志级别为debug

当应用程序启动时,Spring Boot会自动读取application.yml文件中的配置信息,并应用到应用程序中相应的组件中。

以上就是SpringBoot配置文件详解,更多内容请查看:SpringBoot框架教程(详细图文详解)

作者简介

陈睿|mikechen,10年+大厂架构经验,BAT资深面试官,就职于阿里巴巴、淘宝、百度等一线互联网大厂。

👇阅读更多mikechen架构文章👇

阿里架构 |双11秒杀 |分布式架构 |负载均衡 |单点登录 |微服务 |云原生 |高并发 |架构师

以上

关注作者「mikechen」公众号,获取更多技术干货!

后台回复架构,即可获取《阿里架构师进阶专题全部合集》,后台回复面试即可获取《史上最全阿里Java面试题总结

评论交流
    说说你的看法