• 【SpringBoot】配置文件详解


    一. 配置文件作用

    整个项⽬中所有重要的数据都是在配置⽂件中配置的,⽐如:

    • 数据库的连接信息(包含⽤户名和密码的设置);
    • 项⽬的启动端⼝;
    • 第三⽅系统的调⽤秘钥等信息;
    • ⽤于发现和定位问题的普通⽇志和异常⽇志等。

    二. 配置文件的格式

    .properties
    .yml

    在这里插入图片描述

    • 理论上来讲 .properties 可以和 .yml 共存,但实际的业务当中,我们通常会采取⼀种统⼀的配置⽂件格式,这样可以更好的维护(降低故障率)。

    • 当 properties 和 yml ⼀起存在⼀个项⽬中时, .properties 配置⽂件的优先级最⾼,但加载完 .properties ⽂件之后,也会加载 .yml ⽂件的配置信息。

    1. properties 配置文件说明

    properties 配置⽂件是最早期的配置⽂件格式,也是创建 Spring Boot 项⽬默认的配置⽂件。

    ①. properties 基本语法

    properties 是以键值的形式配置的,key 和 value 之间是以 “=” 连接的。

    # 配置项⽬端⼝号
    server.port=8084
    spring.datasource.url=jdbc:mysql://127.0.0.1:3306/dbname?characterEncoding=utf8
    spring.datasource.username=root
    spring.datasource.password=root
    
    • 1
    • 2
    • 3
    • 4
    • 5

    配置⽂件中使⽤“#”来添加注释信息。

    ②. 读取配置⽂件

    使⽤ @Value 注解来实现。@Value 注解使⽤ “${}” 的格式读取。

    @Component
    public class ReadYml {
        @Value("${server.port}")
        private String port;
    
        @PostConstruct
        public void postConstruct() {
            System.out.println("Read YML,port:" + port);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    启动项目:
    在这里插入图片描述

    注意 @Value 属于 Spring 包里面的,不要导错了

    ③. properties 缺点

    properties 配置是以 key-value 的形式配置的,properties 配置⽂件中会有很多的冗余的信息。

    在这里插入图片描述
    想要解决这个问题,就可以使⽤ yml 配置⽂件。

    2. yml 配置⽂件说明

    yml 是 YAML 是缩写,它的全称 Yet Another Markup Language 翻译成中⽂就是“另⼀种标记语⾔”。

    yml 优点分析

    • yml 是⼀个可读性⾼,写法简单、易于理解,它的语法和 JSON 语⾔类似。
    • yml ⽀持更多的数据类型,它可以简单表达清单(数组)、散列表,标量等数据形态。它使⽤空⽩符号缩进和⼤量依赖外观的特⾊,特别适合⽤来表达或编辑数据结构、各种配置⽂件等。
    • yml ⽀持更多的编程语⾔,它不⽌是 Java 中可以使⽤在 Golang、PHP、Python、Ruby、JavaScript、Perl 中。

    ①. yml 基本语法

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

      username: root # 正确
      
      username:root  # 错误
    
    • 1
    • 2
    • 3

    使⽤ yml 连接数据库

    spring:
      datasource:
        url: jdbc:mysql://127.0.0.0:3306/dbname?characterEncoding=utf8
        username: root
        password: root
    
    • 1
    • 2
    • 3
    • 4
    • 5

    ②. yml 使用进阶

    1. yml 配置不同数据类型及 null
    # 字符串
    value1: Hello
    # 布尔值,truefalse
    value2: true
    value3: false
    # 整数
    value4: 10
    value: 0b1010_0111_0100_1010_1110 # ⼆进制
    # 浮点数
    value5: 3.14159
    value6: 314159e-5 # 科学计数法
    # Null,~代表null
    value7: ~
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    对于基本数据类型直接 key: value 即可。

    yml 读取配置的⽅式和 properties 相同,使⽤ @Value 注解即可

    @Component
    public class ReadYml {
        @Value("${value1}")
        private String hello;
        @PostConstruct
        public void postConstruct() {
            System.out.println("Read YML,Hello:" + hello);
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    注意:有可能不让你自己定义属性,在 pom.xml 中加入依赖即可。

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-configuration-processor</artifactId>
                <optional>true</optional>
            </dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    注意事项:value 值加单双引号

    字符串默认不⽤加上单引号或者双引号,如果加英⽂的单双引号可以表示特殊的含义。

    string:
      str1: Hello \n Spring Boot.
      str2: 'Hello \n Spring Boot.'
      str3: "Hello \n Spring Boot."
    
    • 1
    • 2
    • 3
    • 4
    @Component
    public class ReadYml {
        @Value("${string.str1}")
        private String str1;
        @Value("${string.str2}")
        private String str2;
        @Value("${string.str3}")
        private String str3;
        @PostConstruct
        public void postConstruct() {
            System.out.println("string.str1:" + str1);
            System.out.println("string.str2:" + str2);
            System.out.println("string.str3:" + str3);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    在这里插入图片描述

    • 字符串默认不⽤加上单引号或者双引号。
    • 单引号会转义特殊字符,特殊字符最终只是⼀个普通的字符串数据。
    • 双引号不会转义字符串⾥⾯的特殊字符;特殊字符会作为本身想表示的意思。
    1. 配置对象

    我们还可以在 yml 中配置对象,如下配置:

    student:
      id: 1
      name: Java
      age: 18
    
    • 1
    • 2
    • 3
    • 4

    student 直接就是 类名,无类型,哪个类进行读取,那么就是哪个类型。
    或者是使⽤⾏内写法(与上⾯的写法作⽤⼀致):

     student: {id: 1,name: Java,age: 18}
    
    • 1

    这个时候就不能⽤ @Value 来读取配置中的对象了,此时要使⽤另⼀个注解
    @ConfigurationProperties 来读取,具体实现如下:

    @ConfigurationProperties(prefix = "student")
    @Component
    public class StudentComponent {
        private int id;
        private String name;
        private int age;
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
        @Override
        public String toString() {
            return "StudentComponent{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    注意:这里面类的属性名要和 yml 文件中的属性名一致。并且类的属性一定要提供 get、set 方法,配置文件是根据 set 方法将对应的属性赋值的。

    @Component
    public class ReadYml {
        @Autowired
        private StudentComponent studentComponent;
        @PostConstruct
        public void postConstruct() {
            System.out.println(studentComponent);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    在这里插入图片描述

    1. 配置集合

    配置⽂件也可以配置 list 集合

    dbtypes:
      name:
        - mysql
        - sqlserver
        - db2
    
    • 1
    • 2
    • 3
    • 4
    • 5

    dbtypes 表示一个 类名,name 表示类里面有一个 list 名为 name , - 表示一个元素。
    所以这段代码的意思就是有一个类名为 dbtypes,该类里面有一个名为 name 的list, list 里面有 三个值,mysql、sqlserver 和 db2

    或者是使⽤⾏内写法(与上⾯的写法作⽤⼀致):

    dbtypes: {name: [mysql,sqlserver,db2]}
    
    • 1

    集合的读取和对象⼀样,也是使⽤ @ConfigurationProperties 来读取的

    @Component
    public class ReadYml {
        @Autowired
        private ListConfig listConfig;
        @PostConstruct
        public void postConstruct() {
            System.out.println(listConfig.getName());
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    在这里插入图片描述

    3. properties VS yml

    • properties 是以 key=value 的形式配置的键值类型的配置⽂件,⽽ yml 使⽤的是类似 json 格式的树形配置⽅式进⾏配置的,yml 层级之间使⽤换⾏缩进的⽅式配置,key 和 value 之间使⽤“: ”英⽂冒号加空格的⽅式设置,并且空格不可省略。
    • properties 为早期并且默认的配置⽂件格式,但其配置存在⼀定的冗余数据,使⽤ yml 可以很好的解决数据冗余的问题。
    • yml 通⽤性更好,⽀持更多语⾔,如 Java、Go、Python 等,如果是云服务器开发,可以使⽤⼀份配置⽂件作为 Java 和 Go 的共同配置⽂件。
    • yml ⽀持更多的数据类型。

    三. 设置不同环境的配置⽂件

    开发环境和生产环境使用的配置是完全不同的。

    1、创建不同环境的配置⽂件:

    • application-dev.yml

    • application-prod.yml

    这个文件命名的方式是固定的 application 加上 - 再加上 其他名字,用这个名字来区分不同的配置文件。

    2、在 application.yml 中设置运⾏环境

    spring.profiles.active=dev
    
    • 1

    这样表示使用 application-dev.yml 这个配置文件。
    spring.profiles.active=prod 就表示使用 application-prod.yml 这个文件。

  • 相关阅读:
    HTTP超时时间设置
    js创建 ajax 过程
    mysql监控sql执行情况
    uniapp qiun charts H5使用echarts的eopts配置不生效
    CV基础常用知识点
    136 只出现一次的数字
    failed to solve with frontend dockerfile.v0: failed to create LLB definition:
    SAP UI5 指定 / 变更版本
    如何看待Unity新收费模式?
    在20.04.4 LTS (Focal Fossa)学习CommonAPI-C---D-Bus
  • 原文地址:https://blog.csdn.net/m0_61832361/article/details/133554603