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文件中设置属性来配置应用程序。

示例如下:

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

 

2.YAML文件格式

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

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

示例如下:

  1. server:
  2. port: 8080
  3. spring:
  4. datasource:
  5. url: jdbc:mysql://localhost:3306/testdb
  6. username: root
  7. password: 123456

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

 

SpringBoot配置文件示例

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

  1. # 服务端口号
  2. server:
  3. port: 8080
  4.  
  5. # 数据库配置
  6. spring:
  7. datasource:
  8. url: jdbc:mysql://localhost:3306/test?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC&characterEncoding=utf-8
  9. username: root
  10. password: 123456
  11. driver-class-name: com.mysql.cj.jdbc.Driver
  12.  
  13. # MyBatis配置
  14. mybatis:
  15. mapper-locations: classpath:mapper/*.xml
  16. configuration:
  17. map-underscore-to-camel-case: true
  18.  
  19. # 日志配置
  20. logging:
  21. level:
  22. root: info
  23. com.example: debug

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

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

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

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

评论交流
    说说你的看法
欢迎您,新朋友,感谢参与互动!