SpringBoot 配置文件

配置文件的加载优先级:properties>yml>yaml

application.properties 配置

server.port=8080
server.address=localhost
logging.pattern.dateformat=yyyy-MM-dd HH:mm:ss.SSS

application.yml 配置

server:
  port: 4000
spring:
    application:
        name: SpringBootDemo-01
    datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/springbootdemo?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
        username: root
        password: 123456

logging:
  pattern:
    dateformat: yyyy-MM-dd HH:mm:ss.SS
    
baseDir: /home/user
tempDir: ${baseDir}/temp

# 使用引号包裹的字符串,其中的转译字符会生效,例如\t、\n等转译字符
tempDir01: "${baseDir}\temp"

配置文件优先级:.properties > yml > yaml

读取配置

SpringBoot 中读取配置文件有以下5种方法:

  • 使用@Value读取配置文件。

  • 使用@ConfigurationProperties读取配置文件。

  • 使用Environment读取配置文件。

  • 使用@PropertySource读取配置文件。

  • 使用原生方式读取配置文件

使用@Value读取单个配置

@Value用于读取单个属性

使用@ConfigurationProperties读取配置

@ConfigurationProperties用于读取一组数据

使用Environment读取配置

Environment 是 Spring Core 中的一个用于读取配置文件的类,将此类使用 @Autowired 注入到类中就可以使用它的 getProperty 方法来获取某个配置项的值了

使用@PropertySource读取配置

使用@PropertySource注解可以用来指定读取某个配置文件,比如指定读取 application.properties配置文件的配置内容。

中文乱码

如果配置文件中出现中文乱码的情况,可通过指定编码格式的方式来解决中文乱码的问题,具体实现如下:

多环境配置

properties 多环境

创建多环境配置文件时,需遵循Spring Boot允许的命名规范,格式为application-{prifile}.properties,其中profile对应的是环境标识,在项目resource目录下分别创建application-dev.propertiesapplication-test.propertiesapplication-prod.properties三个配置文件,对应开发环境、测试环境和生产环境,如下图所示:

Drawing
  • application.properties为项目住配置文件,包含项目所需的公共配置。

  • application-dev.properties:开发环境配置文件,包含项目所需的单独配置。

  • application-tets.properties:测试环境配置文件。

  • application-prod.properties:生产环境配置文件。

yaml 多环境配置

yaml 配置文件没有办法拆分成多个环境的配置文件,通常是在一个文件中通过---来分割不同环境的配置,示例如下。

多环境切换

通过修改application.properties配置文件中的spring.active配置来激活响应的运行环境,如果没有指定任何profile的配置文件,Spring Boot默认会启动application-default.properties(默认环境)。

指定项目启动环境有以下三种方式:

一、配置文件指定启动环境

在application.properties配置文件中增加如下配置指定对应的环境。

二、通过IDEA编辑器指定项目启动环境

Drawing
IDEA 指定运行环境

三、通过运行命令指定环境

在命令行通过java -jar命令启动项目时,指定启动环境:

多环境开发兼容问题

最后更新于