SpringBoot配置文件(.properties+yml)


SpringBoot中的配置文件

1. 配置文件的作用

整个项⽬中所有重要的数据都是在配置⽂件中配置的,⽐如:
● 数据库的连接信息(包含⽤户名和密码的设置);
● 项⽬的启动端⼝;
● 第三⽅系统的调⽤秘钥等信息;
● ⽤于发现和定位问题的普通⽇志和异常⽇志等

2. SpringBoot 配置文件格式

  1. xxx.properties(默认配置文件的格式)
  2. xxx.yml(新版本、改良版的配置文件格式)
  3. 当一个项目中既有 .properties 又有.yml并且两个配置文件中有相同的配置项,那么Spring Boot项目会采用优先级更高的 .properties配置项作为最终的配置项目。properties格式的配置文件优先级是高于yml的
  4. 一个项目中允许存在两种不同的配置文件 properties 和 yml ,但是不建议在一个项目中只采取两种格式的配置文件
    社区版的 idea 需要安装 Spring Tools插件之后,使用 properties配置项才会有代码提示

properties基本语法

properties 是以键值的形式配置的,key 和 value 之间是以“=”连接的,如果是自己的配置信息,那么你可以在遵循 key=value的格式下,定义任何名称的Key

#端口号
server.port=7070
#数据库的配置信息
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/database_name?characterEncoding=utf8&useSSL=false
spring.datasource.name=root
spring.datasource.password=root

读取配置文件

如果在项目中,想主动的读取配置文件中的内容,可以使用 @Value 注解来 实现
@Value 注解使用 “${}”的格式读取,如下代码所示:

@Component
public class ReadProperties {
    
    
    @Value("${server.port}")
    String port;
    @Value("${spring.datasource.url}")
    String url;

    // 初始化时执行的方法
    @PostConstruct
    public void printInfo() {
    
    
        System.out.println();
        System.out.println(this.port);
        System.out.println(this.url);
        System.out.println();
    }
}

@Component 在 Spring Boot 启动时候会注⼊到框架中,注⼊到框架中时会执⾏ @PostConstruct 初
始化⽅法,这个时候就能读取到配置信息了

运行结果

在这里插入图片描述

properties 缺点分析

  1. 对于一个对象的多个参数设置很麻烦,需要从开始写起一直写到结束为止
  2. 存在冗余的配置项
    在这里插入图片描述
    想要解决这个问题,就可以使⽤ yml 格式的配置⽂件了

3. yml配置文件的使用

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

yml基本语法

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

注意:冒号后面一定要接一个空格!
第二级和上一级需要两个空格

server:
  port: 6060
spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/database_name?characterEncoding=utf8&useSSL=false
    name: root

在这里插入图片描述

配置对象

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

student:
  id: 1
  name: 张三
  age: 18

还有另外一种类似于 JSON 的写法,注意加空格

student: {
    
    id: 1,name: 张三,age: 18}

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

读取配置文件方式2:@ConfigurationProperties 读取一个实体类

1.将配置文件中的一组对象映射到某个类上

注意一定要加上 get、set方法不然无法映射,且对象名要和配置文件中对应

@Component//spring 启动时直接将配置文件映射到当前类属性
@ConfigurationProperties(prefix = "student")//配置yml文件中的key,prefix可以省略
public class Student {
    
    
    private int id;
    private String name;
    private int age;


    @Override
    public String toString() {
    
    
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + 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;
    }
}

2.使用注入的方式在其它类中注入即可

@Component
public class ReadYml {
    
    
    @Autowired
    Student student;

    @PostConstruct
    public void printInfo() {
    
    
        System.out.println();
        System.out.println(student);
        System.out.println();
    }
}

启动SpringBoot运行结果

在这里插入图片描述

配置集合

配置⽂件也可以配置 list 集合,如下所示
注意:空格!

lists:
  language:
    - java
    - python
    - c++
    - golang

和配置对象类似,可以写长行内写法

lists: {
    
    language: [java,python,c++,golang]}

集合的读取和对象⼀样,也是使⽤ @ConfigurationProperties 来读取的,具体实现如下:
注意一定要加上 get、set方法不然无法映射,且对象名要和配置文件中对应

在这里插入图片描述

@Component// spring启动时直接将配置文件映射到类属性
@ConfigurationProperties("lists")
public class MyList {
    
    
    private List<String> language;

    public List<String> getLanguage() {
    
    
        return language;
    }

    public void setLanguage(List<String> language) {
    
    
        this.language = language;
    }
}

使用注入的方式在其它类中注入即可

@Component
public class ReadYml {
    
    
    @Resource
    private MyList myList;
    @PostConstruct
    public void printInfo() {
    
    
        System.out.println();
        System.out.println(myList.getLanguage());
        System.out.println();
    }
}

运行结果

在这里插入图片描述

yml 配置不同数据类型及 null

# 字符串
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: 

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

yml配置文件内容

str1: hello\nworld
str2: 'hello\nworld'
str3: "hello\nworld"

读取配置文件并打印

@Component
public class ReadYml {
    
    
    @Autowired
    private Student student;
    @Resource
    private MyList myList;
    @Value("${str1}")
    private String str1;
    @Value("${str2}")
    private String str2;
    @Value("${str3}")
    private String str3;
    @PostConstruct
    public void printInfo() {
    
    
        System.out.println();
        System.out.println(str1);
        System.out.println(str2);
        System.out.println(str3);
        System.out.println();
    }
}

运行结果

在这里插入图片描述

  1. 如果是string 类型可以不加单引号或者双引号
  2. 如果加了单引号和不加(任何符号)的效果是一样的,它会转义字符串中的特殊符号,让它变成普通字符
  3. 如果加了双引号,那么字符串的特殊字符是不会转义的,会按照语义正确执行,比如上面的 \n 会变成换行

4. properties vs yml

  1. yml 语法更简洁
  2. yml 跨语言的通用性更好,它不止支持 Java 语言还支持golang和python
  3. yml支持更多的数据类型
  4. yml格式的配置文件在写的时候更容易出错,而 properties它虽然写法比较传统和复杂,但它不容易出错
  5. properties的优先级更高

5.SpringBoot中读取配置文件的5种方式

假设要读取配置文件中的 server.port

使用@Value

@Component
public class ReadProperties {
    
    
    @Value("${server.port}")
    String port;
    // 初始化时执行的方法
    @PostConstruct
    public void printInfo() {
    
    
        System.out.println();
        System.out.println(this.port);
        System.out.println();

    }

}

使用 @ConfigurationProperties读取配置文件(获取对象)

@Component//spring 启动时直接将配置文件映射到当前类属性
@ConfigurationProperties(prefix = "student")//配置yml文件中的key,prefix可以省略
public class Student {
    
    
    private int id;
    private String name;
    private int age;


    @Override
    public String toString() {
    
    
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + 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;
    }
}

使用 Environment 读取配置为文件

org.springframework.core.env.Environment 的 Environment 对象
使用 Environment 的 getProperty给定参数配置文件的 key值, 来读取配置文件

@Component
public class ReadProperties {
    
    
    @Resource
    private Environment environment;
    // 初始化时执行的方法
    @PostConstruct
    public void printInfo() {
    
    
        System.out.println();
        System.out.println(environment.getProperty("server.port"));
        System.out.println();

    }

}

@PropertySource

使用 @PropertySource 注解可以用来指定读取某个配置文件,比如指定读取 app.properties 配置文件的配置内容
比如我有多个 properties 配置文件,就需要指定读取另外一个配置文件的名称
注意:@PropertySource ,默认只能读取.properties的配置文件。

在这里插入图片描述

@Component
@PropertySource("app.properties")//读取指定配置文件
public class ReadProperties {
    
    
    @Value("${server.port}")
    private String port;

    // 初始化时执行的方法
    @PostConstruct
    public void printInfo() {
    
    
        System.out.println();
        System.out.println(this.port);
        System.out.println();
    }

}

如果出现乱码

@PropertySource(value = "dev.properties", encoding = "utf-8")

再设置idea的字符集

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

@Component
@PropertySource("app.properties")//读取指定配置文件
public class ReadProperties implements InitializingBean {
    
    

    @Override
    public void afterPropertiesSet() throws Exception {
    
    
        Properties properties = new Properties();
        try (InputStreamReader inputStreamReader = new InputStreamReader
                (this.getClass().getClassLoader().getResourceAsStream("app.properties"),StandardCharsets.UTF_8)) {
    
    
                    properties.load(inputStreamReader);
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
        System.out.println();
        System.out.println(properties.getProperty("server.port"));
        System.out.println();
    }
}

6.多环境配置文件

实际开发中往往会有多个配置文件,至少有三个,开发环境、线上环境和默认配置文件
不同环境配置一个文件,每次只需要更改 application.properties中的配置文件即可

# 设置配置文件的环境 (开发环境 OR 生产环境)
spring.profiles.active=dev

application 和 .格式是固定格式,-后面的才是自定义名字,比如这里就是指定application-port.properties为配置文件
在这里插入图片描述

更多系统配置项目Spring官网


猜你喜欢

转载自blog.csdn.net/weixin_53946852/article/details/129748398