Spring Boot—配置文件

377 阅读7分钟

1、操作环境

  1. OS:WIN10
  2. Java Version: Java 8
  3. Spring Boot Version: 2.7.11
  4. IDEA:IntelliJ IDEA 2022.2.2 (Ultimate Edition)

2、配置文件的格式

Spring Boot配置文件主要分为两种格式, 分别是:.properties.yml, 如下图所示:

image-20230502105432003

3、两种配置文件的区别

  1. .properties类型的配置文件属于xml时代的产物,而.yml属于新时代的产物,这就是好像连锁店⾥⾯的统⼀服装⼀样,有两种不同的款式,properties 类型的配置⽂件就属于⽼款“服饰”,⽽ yml 属于新版款式。

  2. properties 类型的配置⽂件是创建 Spring Boot 项目时默认的文件格式,而yml 类型的配置⽂件需要手动创建

  3. 理论上讲, properties 可以和 yml ⼀起存在于⼀个项⽬当中,当 properties 和 yml ⼀起存在⼀个项目中时,如果配置⽂件中出现了同样的配置,⽐如 properties 和 yml 中都配置了“server.port”,那么这个时候会以 properties 中的配置为主,也就是 .properties 配置⽂件的优先级最⾼,但加载完.properties ⽂件之后,也会加载 .yml ⽂件的配置信息。

    • 例一:在properties 和 yml配置文件中都设置server.port,观察启动时绑定的是哪个配置文件的端口号。

      image-20230502110415168

      image-20230502110457747

      image-20230502110732214

      结论:从测试可知,在properties 和 yml配置文件中设置同样的属性时,会加载properties文件 文件中共有的属性,忽略yml文件中共有的属性

    • 例二:当properties 和 yml配置文件同时存在,且yml文件中有特有的属性,观察是否会读取yml中特有的属性。

      image-20230502111746069

      image-20230502111621114

      image-20230502111823156

      结论:从测试可知,当properties 和 yml配置文件同时存在,是会读取yml中的特有属性。

  4. 虽然理论上来讲 properties 和 yml配置文件可以共存,但实际的业务当中,不建议这么做,而是通常会采取⼀种统⼀的配置⽂件格式,这样可以更好的维护(降低故障率)。

4、properties配置文件的使用

4.1 基本语法

properties 是以键值的形式配置的,key 和 value 之间是以“=”连接的。key、value和”=“,以及value后面不要有空格存在,否则有时会出现读取错误

  • 规范写法

    server.port=8080
    spring.datasource.url=jdbc:mysql://127.0.0.1:3306/testdb?
    spring.datasource.username=root
    spring.datasource.password=root
    
  • 不规范写法!

4.2 读取配置文件

如果在项⽬中,想要主动的读取配置⽂件中的内容,可以使⽤@Value 注解来实现@Value 注解使⽤“${}”的格式读取

  • 示例

    # properties 配置文件
    server.port=8080
    spring.datasource.url=jdbc:mysql://127.0.0.1:3306/testdb?
    spring.datasource.username=root
    spring.datasource.password=root
    
    package com.example.spring_boot;
    
    import com.example.spring_boot.ref.MyList;
    import com.example.spring_boot.ref.Student;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import java.util.List;
    
    @Controller
    public class UserController {
        // 读取application.properties配置文件的普通属性
        @Value("${spring.datasource.username}")
        private String root;
    
        @ResponseBody // 返回一个非静态页面的数据
        @RequestMapping("/sayhi") // 设置路由地址, 必须全部小写
        public String sayHi() {
            System.out.println(root);
            return "hello, world!";
        }
    }
    
    

    image-20230502113552031

4.3 缺点

properties 配置是以 key-value 的形式配置的,如下图所示:

image-20230502113730301

从上述配置key看出,properties配置文件中有很多冗余的信息,如下图所示:

image-20230502113943315

想要解决这个问题,就可以使⽤ yml 配置⽂件的格式化了。

5、yml配置文件的使用说明

5.1 介绍

​ yml 是 YMAL 是缩写,它的全称 Yet Another Markup Language 翻译成中⽂就是“另⼀种标记语⾔”。yml 是⼀个可读性⾼,易于理解,⽤来表达数据序列化的格式。它的语法和其他⾼级语⾔类似,并且可以简单表达清单(数组)、散列表,标量等数据形态。它使⽤空⽩符号缩进和⼤量依赖外观的特⾊,特别适合⽤来表达或编辑数据结构、各种配置⽂件等。yml 最大的优势是可以跨语言,不止是 Java 中可以使⽤ golang、python 都可以使用 yaml 作为配置⽂件。

5.2 基本语法

  • yml 是树形结构的配置⽂件,它的基础语法是“key: value”,注意 key 和 value 之间使⽤英⽂冒号加空格的⽅式组成的,其中的空格不可省略。如下图所示:

image-20230502170857653

  • 当多个key前面部分有重叠部分,可以省略,如下图所写,这也是yml文件优于properties的地方。

    例如,使用yml链接数据库,yml文件为

    image-20230502172103296

    ​ properties文件为: image-20230502172032563

  • yml可以配置不同数据类型及null(properties文件不可以)

    # 字符串
    string.value: Hello
    
    # 布尔值,true或false
    boolean.value: true
    boolean.value1: false
    # 整数
    int.value: 10
    int.value1: 0b1010_0111_0100_1010_1110 # ⼆进制
    # 浮点数
    float.value: 3.14159
    float.value1: 314159e-5 # 科学计数法
    # Null,~代表null
    null.value: ~
    

5.2 读取配置文件

5.2.1 读取普通属性

  • 对于一般属性,yml读取配置方式和properties方式一致,都是使用@Value("${}")形式。实现代码如下:

    # yml配置文件
    # 普通属性
    server.port: 8081
    
    package com.example.spring_boot;
    
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    @Controller
    public class UserController {  
        // 读取application.yml配置文件的普通属性
        @Value("${server.port}")
        private String port;
        
        @ResponseBody // 返回一个非静态页面的数据
        @RequestMapping("/sayhi") // 设置路由地址, 必须全部小写
        public String sayHi() {
            System.out.println(port);
            return "hello, world!";
        }
    }
    

    执行结果:

    image-20230502173513963

注意:

  • 如果value值为字符串时,字符串默认不加单引号,或者双引号,如果加了会转义特殊字符

    实现代码如下:

    # yml文件
    # 下面这三种都表示字符串
    string:
     str1: Hello \n Spring Boot.   
     str2: 'Hello \n Spring Boot.'
     str3: "Hello \n Spring Boot."
    
    package com.example.spring_boot;
    
    import com.example.spring_boot.ref.MyList;
    import com.example.spring_boot.ref.Student;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import java.util.List;
    
    @Controller
    public class UserController {
    
        // 读取application.yml配置文件的普通属性
        @Value("${server.port}")
        private String port;
    
        @Value("${string.str1}")
        private String str1; 
        
        @Value("${string.str2}")
        private String str2;
    
        @Value("${string.str3}")
        private String str3;
         
        @ResponseBody // 返回一个非静态页面的数据
        @RequestMapping("/sayhi") // 设置路由地址, 必须全部小写
        public String sayHi() {
            System.out.println(str1);
            System.out.println(str2);
            System.out.println(str3);
            return "hello, world!";
        }
    }
    

    **执行结果:**加双引号的字符串中的特殊字符被转义。

    image-20230502174430170

5.2.1 读取对象属性

  1. 第一步:配置对象属性。一般有两种配置方式,配置方式如下:

    # yml文件
    # 第一种配置方式
    student1:
     id: 1
     name: Java
     age: 18
    
    # 第二种配置方式(推荐)
    student2: {id: 1,name: Java,age: 18} 
    

    image-20230502180428641

  2. 第二步:在配置文件所在路径创建一个类

    package com.example.spring_boot.ref;
    
    import lombok.Data;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.stereotype.Component;
    
    @Data
    @Component
    @ConfigurationProperties(prefix = "student1")
    public class Student {
        private int id;
        private String name;
        private int age;
    }
    

    image-20230502175849983

  3. 第三步:在被注入类中,对象注入

    package com.example.spring_boot;
    
    import com.example.spring_boot.ref.MyList;
    import com.example.spring_boot.ref.Student;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import java.util.List;
    
    @Controller
    public class UserController {
        // 读取application.yml文件的对象属性
        @Autowired
        private Student stu;
    
    
        @ResponseBody // 返回一个非静态页面的数据
        @RequestMapping("/sayhi") // 设置路由地址, 必须全部小写
        public String sayHi() {
    //        System.out.println(stu.toString());
            return "hello, world!";
        }
    }
    

    image-20230502180100066

  4. 启动项目,执行结果如下:

    image-20230502180523360

5.2.2 读取集合属性

  1. 第一步:配置集合属性。一般有两种配置方式,配置方式如下:

    # yml文件
    # 第一种配置方式
    dbtypes:
     name:
       - mysql
       - sqlserver
       - db2
    
    # 第二种配置方式(推荐)
    dbtypes: {name: [mysql,sqlserver,db2]}
    

    image-20230502205228032

  2. 第二步:在配置文件所在路径创建一个类

    package com.example.spring_boot.ref;
    
    import lombok.Data;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.stereotype.Component;
    
    import java.util.List;
    
    @Component
    @Data
    @ConfigurationProperties(prefix="dbtypes") // 可以不写prefix, 默认是prefix
    public class MyList {
        public List<String> name; // 该属性的名字要和yml文件中集合的名字相对应
    
    }
    
  3. 第三步:在被注入类中,对象注入

    package com.example.spring_boot;
    
    import com.example.spring_boot.ref.MyList;
    import com.example.spring_boot.ref.Student;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import java.util.List;
    
    @Controller
    public class UserController {
        // 读取application.yml文件的集合属性
        @Autowired
        private MyList myList;
    
        @ResponseBody // 返回一个非静态页面的数据
        @RequestMapping("/sayhi") // 设置路由地址, 必须全部小写
        public String sayHi() {
            System.out.println(myList.getName());
            return "hello, world!";
        }
    }
    

    image-20230502180100066

  4. 启动项目,执行结果如下:

    image-20230502205551173

6. properties和yml配置文件总结

  1. properties 是以 key=value 的形式配置的键值类型的配置⽂件,⽽ yml 使⽤的是类似 json 格式进⾏配置的,yml 层级之间使⽤换⾏缩进的⽅式配置,key 和 value 之间使⽤“: ”英⽂冒号加空格的⽅式设置,并且空格不可省略。

  2. properties 为早期并且默认的配置⽂件格式,但其配置存在⼀定的冗余数据,使⽤ yml 可以很好的解决数据冗余的问题。

  3. yml 通⽤性更好,⽀持更多语⾔,如 Java、Go、Python 等,如果是云服务器开发,可以使⽤⼀份配置⽂件作为 Java 和 Go 的共同配置⽂件。

  4. yml 虽然可以和 properties 共存,但⼀个项⽬中建议使⽤统⼀的配置类型⽂件。