SpringBoot配置文件的注入和读取

目录

1. 配置文件的作用

2. 两种配置文件的格式:

2.1 properties 基本语法:

2.1.1 写入

2.1.2 读取

执行原理

2.1.3 缺点分析

2.2 yml 基本语法:

2.2.1 写入(非对象)

2.2.3 配置对象

2.2.4 配置集合

多个配置文件



1. 配置文件的作用

        SpringBoot 是为了简化 Spring 的操作,提高 Spring 项目的开发效率,它将 Spring 的一系列组件及配置进行封装和自动调用,但一些重要配置还是需要我们手动配置的,例如数据库接口、账户密码、项目端口、异常日志等由开发环境所决定的信息。

2. 两种配置文件的格式:

        SpringBoot 配置文件有两种格式:.properties 和 .yml,二者的区别可以简单理解为:

        首先:二者的功能都是一样的,.properties 文件是最早期的文件格式, 也是SpringBoot 的默认文件,项目诞生之初就自带的,而 .yml 是后来为了提高效率而衍生出的另一种格式,它相对于前者更写法更简洁,功能更强大,但唯一的不足在于新手容易写错,工作中最常用的是 .yml格式。

        其次:这两种文件在一个项目中理论上可以同时存在,但一般开发不会这样使用,尽量统一使用一种,因为这两种文件都存在的情况下,框架会优先加载 properties 文件,另一方面统一有助于代码的读写。

        不管使用哪种配置文件,文件建立之初它们都是空白的,具体要配置哪些功能随着我们开发自行配置即可,配置同时又分为了 “写入配置文件” 和 “读取配置文件” 两步。        

2.1 properties 基本语法:

2.1.1 写入:

         properties 文件是键值对形式,key 和 value 之间用 “=” 连接:

#配置项目端口
server.port=8080

#配置数据库连接
spring.datasource.url=jdbc:mysql://127.0.0.1/3306/blog?characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=111111

2.1.2 读取:

        properties 文件的读取使用 @Value("${}") :        

@Controller
public class ReadProperties {
    @Value("${server.port}")
    private String port;

    @PostConstruct
    public void postConstruct() {
        System.out.println("port -> " + port);
    }
}

执行效果:

执行原理:

        @Controller 将当前 Bean 存到容器中,在执行 @PostConstruct 方法时就可以读到配置信息;

2.1.3 缺点分析:

         像这样,properties 文件可能有时需要写多次冗余的内容,因此 yml 文件就解决了这点。

2.2 yml 基本语法:

        yml文件需要先手动创建:

2.2.1 写入(非对象):

        yml 是树形配置文件,语法格式为:key: value观察颜色,冒号和 value 之间是有空格的,这就是容易写错的地方。如果在书写时格式正确,key: 也会自动高亮。

#配置项目端口
server:
  port: 8080

#配置数据库连接
spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/blog?characterEncoding=utf8
    username: root
    password: 111111

各种类型的写法:其实 yml不仅是一种文件,还是一种配置语言,因此其支持更广泛的数据类型。

#整数
int.value1: 1
int.value2: 2
int.value3: 3

#浮点数
float.value1: 3.1415
float.value2: 1.69

#字符串
string.value: hello world

#布尔值
boolean.value1: true
boolean.value2: false

# null值,yml 的 null 代表什么都是也代表什么都不是
null.value: ~

注意点:字符串加单/双引号前后含义不同:

#特殊的字符串
string:
    none: hello /n world
    single: 'hello \n world'
    doub: "hello \n world"
@Controller
public class ReadYmlStr {
    @Value("${string.none}")
    private String none;

    @Value("${string.single}")
    private String single;

    @Value("${string.doub}")
    private String doub;

    @PostConstruct
    public void postConstruct() {
        System.out.println("不加引号:" + none);
        System.out.println("加单引号:" + single);
        System.out.println("加双引号:" + doub);
    }
}

  • 字符串默认不加引号;
  • 加单引号,会转义特殊字符为普通字符;
  • 加双引号,不会转义特殊字符;

2.2.2 读取:

        yml 的读取和 properties 一样,也是通过 @Value("${}") 实现:

@Controller
public class ReadYml {
    @Value("${int.value1}")
    private int num;

    @Value("${string.value}")
    private String str;

    @Value("${boolean.value1}")
    private boolean ans;

    @PostConstruct
    public void postConstruct() {
        System.out.println("从Yml里拿到的num为:" + num);
        System.out.println("从Yml里拿到的str为:" + str);
        System.out.println("从Yml里拿到的ans为:" + ans);
    }
}

2.2.3 配置对象:

写入对象:

        写入对象的语法有两种:①普通的,按照yml格式写;②行内样式写法;

①yml 格式:

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

②行内样式:

teacher: {id: 1, name: 张红, age: 25}

接着需要在对象依赖的类里加入注解:@ConfigurationProperties("")

另外一定不能缺少对象的 Getter() 和 Setter() 方法,这里只能借助 lombok注解简化了代码

// 关键注解是第一句,中间三个注解是 lombok 的注解,
// Getter 和 Setter 相关方法不能少
@ConfigurationProperties("student")
@Getter
@Setter
@ToString
@Component
public class Student {
    private int id;
    private String name;
    private int age;
}

读取对象:读取没有特殊的,还是要通过 @Autowired 属性注入的方式:

@Component
public class ReadObjects {
    @Autowired
    private Student student;

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

2.2.4 配置集合:

写入:

写入也有两种格式:

①普通yml格式:

dogtypes:
  dogsName:
    - 泰迪
    - 比熊
    - 博美
    - 爱斯基摩
    - 哈士奇
    - 边牧
    - 萨摩耶
@ConfigurationProperties("dogtypes")
@Getter
@Setter
@ToString
@Component
public class ListConfig {
    private List<String> dogsName;
}

②行内样式:

cattypes: {catsName: [中华田园猫,英短,加菲,布偶,金吉拉]}
@ConfigurationProperties("cattypes")
@Getter
@Setter
@ToString
@Component
public class ListConfig2 {
    private List<String> catsName;
}

读取:

@Component
public class ReadList {
    @Autowired
    private ListConfig listConfig;

    @PostConstruct
    public void postConstruct() {
        System.out.println(listConfig.getDogsName());
    }
}


多个配置文件:

        开发分了很多环境:开发环境、测试环境等,还可以分得更细,对于不同环境可以配置不同的配置文件,但前提是要有一个总配置文件;

        一般总配置文件命名为:application.yml;其他配置文件根据环境命名;

        主配置文件可以调用子配置文件:

关于更多 SpringBoot 读取配置文件等操作:面试突击75:SpringBoot 有几种读取配置文件的方法? - 掘金


猜你喜欢

转载自blog.csdn.net/m0_65190367/article/details/130876128