Injection and reading of SpringBoot configuration files

Table of contents

1. The role of the configuration file

2. Two configuration file formats:

2.1 properties basic syntax:

2.1.1 Write

2.1.2 Read

Principle of execution

2.1.3 Shortcoming Analysis

2.2 Basic syntax of yml:

2.2.1 Write (non-object)

2.2.3 Configuration objects

2.2.4 Configuration collection

multiple configuration files



1. The role of the configuration file

        SpringBoot is to simplify the operation of Spring and improve the development efficiency of Spring projects. It encapsulates and automatically calls a series of Spring components and configurations, but some important configurations still require manual configuration, such as database interfaces, account passwords, and project ports. , exception logs and other information determined by the development environment.

2. Two configuration file formats:

        There are two formats of SpringBoot configuration files: .properties and .yml. The difference between the two can be simply understood as:

        First of all: the functions of the two are the same. The .properties file is the earliest file format and the default file of SpringBoot. It comes with the project at the beginning of its birth, and .yml is another derived later to improve efficiency. Compared with the former, it is more concise in writing and more powerful in function, but the only disadvantage is that it is easy for novices to make mistakes, and the .yml format is most commonly used in work.

        Secondly: These two files can theoretically exist at the same time in a project, but generally development will not be used in this way, try to use one uniformly, because when both files exist, the framework will load the properties file first, and the other Aspect unification helps read and write code.

        No matter which configuration file is used, they are blank at the beginning of the file creation. The specific functions to be configured can be configured as we develop. The configuration is also divided into "write configuration file" and "read configuration file". step.        

2.1 properties basic syntax:

2.1.1 Write:

         The properties file is in the form of key-value pairs, and the key and value are connected with "=":

#配置项目端口
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 Read:

        Properties file is read using @Value("${}"):        

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

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

Execution effect:

Execution principle:

        @Controller saves the current Bean in the container, and can read the configuration information when executing the @PostConstruct method;

2.1.3 Disadvantage analysis:

         Like this, the properties file may sometimes need to write redundant content multiple times, so the yml file solves this.

2.2 Basic syntax of yml:

        The yml file needs to be created manually first:

2.2.1 Write (non-object):

        yml is a tree configuration file, the syntax format is: key: value , observe the color, there is a space between the colon and the value, this is where it is easy to make mistakes. key: is also automatically highlighted if the format is correct when writing.

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

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

Various types of writing: In fact, yml is not only a file, but also a configuration language, so it supports a wider range of data types.

#整数
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: ~

Note: Strings with single/double quotes have different meanings before and after:

#特殊的字符串
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);
    }
}

  • Strings are not quoted by default;
  • Adding single quotes will escape special characters into ordinary characters;
  • Add double quotes, special characters will not be escaped;

2.2.2 Read:

        The reading of yml is the same as properties, and it is also implemented through @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 Configuration object:

Write object:

        There are two syntaxes for writing objects: ① Ordinary, written in yml format; ② Inline style writing;

①yml format:

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

②Inline style:

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

Then you need to add annotations to the classes that the objects depend on: @ConfigurationProperties("")

In addition, the Getter() and Setter() methods of the object must not be missing. Here, the code can only be simplified with the help of lombok annotations

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

Read object: There is no special way to read, or to inject it through the @Autowired attribute:

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

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

2.2.4 Configuration collection:

write:

Write also has two formats:

①Common yml format:

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

②Inline style:

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

read:

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

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


Multiple configuration files:

        Development is divided into many environments: development environment, test environment, etc., and can be divided into more detailed ones. Different configuration files can be configured for different environments, but the premise is that there must be a general configuration file;

        The general configuration file is named: application.yml; other configuration files are named according to the environment;

        The main configuration file can call sub-configuration files:

 

About more operations such as SpringBoot reading configuration files: Interview Assault 75: How many ways does SpringBoot have to read configuration files? - Nuggets


Guess you like

Origin blog.csdn.net/m0_65190367/article/details/130876128