SpringBoot可用的配置文件类型

SpringBoot可以使用两种类型的配置文件,分别为.properties和.yml类型的,默认命名分别为application.properties和application.yml。

配置文件的存放位置以及读取顺序

SpringBoot的配置文件如果存放在以下四个位置是可以默认读取到的:

  • 项目的根目录
  • 项目根目录的conf文件夹下
  • 项目resources目录下
  • 项目resources目录的conf文件夹下
    读取顺序是:项目的根目录->项目根目录的conf文件夹下->项目resource目录下->项目resource目录的conf文件夹下

下图中标明了以上的四个位置

备注:

  • 如果同一个目录下,有application.yml也有application.properties,默认先读取application.properties。
  • 如果同一个配置属性,在多个配置文件都配置了,默认使用第1个读取到的,后面读取的不覆盖前面读取到的。
  • 创建SpringBoot项目时,一般的配置文件放置在“项目的resources目录下”。

自定义参数

我们不光可以在配置文件中填写starter包含的配置项内容,也可以根据我们的实际需求,编写自定义的参数,例如

student.name=xiaoming
student.sex=man
student.home=root/src/main/resources/conf/application.properties

然后在程序中可以通过@ConfigurationProperties(prefix = "student")来获取到配置文件的值,不过@ConfigurationProperties要与@Component一起使用才会生效,因为它只能为IOC容器中的对象赋值。

@Component
@ConfigurationProperties(prefix = "student")
public class Student {

    private String name;

    private String sex;

    private String home;

    public Student() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getHome() {
        return home;
    }

    public void setHome(String home) {
        this.home = home;
    }
}

参数引用

配置文件中的参数是可以相互引用的,在一定程度上提高了配置文件种变量的复用性。
示例:

student.name=xiaoming
student.sex=man
student.home=root/application.properties
student.description=I am ${student.name}

使用随机数

在实际开发中,我们经常需要一些随机数,SpringBoot的配置文件也是支持的。
示例:

# 随机字符串
student.random-str=${random.value}
# 随机长整型
student.random-long=${random.long}
# 随机整型
student.random-int=${random.int}
# 范围内随机数
student.random-in-range=${random.int[0,100]}

常用数据结构

SpringBoot的配置文件也支持list和map的赋值。

  • yml的list赋值示例
    student:
    hobby: writing,coding
  • properties的list赋值
    student.hobby=coding,writing
  • yml的map赋值
    student:
    param-map:
      key1: key1
      key2: key2
  • properties的map赋值
    student.param-map.key1=key1
    student.param-map.key2=key2

多环境配置

在实际开发中,我们的项目需要部署在很多环境,比如说开发环境,测试环境以及生产环境,这个时候需要使用到多个配置文件,SpringBoot也是可以支持多配置文件的。
在Spring Boot中多环境配置文件名需要满足application-{profile}.properties的格式,其中{profile}对应你的环境标识,比如:

  • application-dev.properties:开发环境
  • application-test.properties:测试环境
  • application-prod.properties:生产环境

至于哪个具体的配置文件会被加载,需要在application.properties文件中通过spring.profiles.active属性来设置,其值对应配置文件中的{profile}值。如:spring.profiles.active=test就会加载application-test.properties配置文件内容,也可以在jar包启动时指定,例如:java -jar xx.jar --spring.profiles.active=test。

完整的工程代码链接:https://github.com/youzhihua/springboot-training