Spring Boot configuration file [you can see it at a glance]

Spring Boot configuration file

​ This article has entered an important part of Spring Boot, which is about the configuration of Spring Boot, because important data in the entire project are configured in the configuration file.

1. The role of the configuration file

1. Database connection information

​ When I was in JDBC before, the connection information in the database was hard-coded in the code, and the portability was poor. If the project is complicated, it is easy to make mistakes when modifying the JDBC code in it, but the keywords and required information are directly in the configuration file. (Username Password). It is also easy to check and modify the connection information when the operation and maintenance is modified or tested later.

2. The startup port of the project

​ When the port is occupied, you only need to make changes in the configuration file, especially the port 8080 may always be occupied, the previous solution is to find the application that occupies the port 8080 and close it for him, which will cost a lot Still troublesome.

3. Information such as the third-party system call key

​ In a project of Company A, third-party systems or software may be used together to give users a complete experience, such as attendance and online classes. Company A has built a website system to check the attendance rate of students in class , but the video software used by students in class is made by Company B, such as Tencent Classroom, Goose Communication... For these video software, Company A knows its student users, but Company B does not. In order to protect user data The security company B will not hand over user information easily, so for better handover, company B will generate a secret key to company A, and company A will write the secret key in the configuration file when calling company B interface, company B knows that the person of company A can give the user information to company A. The configuration file can be encrypted, and it can also be placed remotely. Even if the hacker gets the source code, he cannot see the content of the configuration information, but if it is written in the code, it may be very dangerous. Calling the secret key in the configuration information is efficient, low-cost, and secure.

4. Common logs and exception logs for finding and locating problems, etc.

​ Logs and exception information can be configured, and the code program error can be located to the exception information to troubleshoot the key log of the problem.

2. Configuration file format

Spring Boot configuration files have two formats

  • .properties
  • .yml

image-20230722172831873

​ These two are configuration files. When the previous name is application, when the Spring Boot project starts, it will read the information in the configuration file. Of course, you can also set other names, but if not application, Spring When the Boot project starts, it does not directly read the configuration file; don't ask why it is the Spring Boot convention, its design principle is that the convention is greater than the configuration

Both properties and yml are configuration files. The difference is that they are products of two different eras. Properties is the boss, which is the default file format of the Spring Boot project. yml belongs to the new version, and the two are the differences between versions.

Special Note:

1. When both configuration files are placed in the Spring Boot project, Spring Boot will give priority to .properties configuration, which means that .properties has a higher priority, and .properties will be loaded first before loading .yml configuration file.

Let me mention here that although .properties has a high priority, it is recommended to use .yml files, and the advantages and disadvantages will be explained later.

2. Although it is said that two location files can coexist, it is enough to use one configuration file in actual business, which will lead to better maintenance and reduce the error rate.

When the two files coexist, the .properties configuration files are all annotated, and the startup class will report an error and fail to start. Either do not move the code inside, or delete one of the configuration files.

2.1. Install the configuration file prompt plug-in

​ Community version of .properties does not have code prompts when writing configuration files (yml has them). Installing the plug-in is for better and more convenient writing of code. It is recommended to install the plug-in.

image-20230722174649454

Three, properties configuration file

3.1, properties basic syntax

server.port=9999
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/javabookmanage?characterEncoding=utf8&useSSL=false"
spring.datasource.username=root
spring.datasource.password=0123456789
# 假如读取腾讯视频秘钥
Tengxun.token=tengxunshiping

​ .properties is configured in the form of key-value pairs, and the key and value are connected by "=". Here is a point to noteDo not add "space" after the equal sign or at the end of the code, Adding a "space" after the equal sign will report an error. Although adding a "space" after the code can be executed, when it is a password, the system will automatically add a "space" at the end, so that the database cannot be connected.

Another disadvantage of .propereties is that the last three paragraphs spring.datasourcewill appear redundant, but it must be written like this.

3.2, read the configuration file

To read the configuration file information, a new annotation is required @Value, which is specially used to read the key in the configuration file, but the syntax in it needs to be added ${}and complete @Value("${key}"), so that Spring Boot can read the key in the configuration file.

@Controller 
@RequestMapping("/index") 
public class HelloController {
    
    

    @Value("${Tengxun.token}") // @Value 是专门读取配置文件 key 【key=Tengxun.token】
    private String tengxunToken;

    @RequestMapping("/tengxun") // localhost:9999/index/tengxun
    @ResponseBody
    public String getTengXunToken() {
    
    
        return tengxunToken;
    }

Note: @Value must be written in this format, and @ResponseBody must be added to the method. Of course, you can also add @ResponseBody to the class to avoid forgetting.

The result is: tengxunshiping, read the value of the key (Tengxun.token) in the configuration file.

Disadvantage analysis of .properties:

1. The code may appear redundant and repetitive;

2. The detail "space" cannot be added, and it may be added accidentally in many cases, and you will not notice it when programming, and you will not know what is wrong when you finally report an error.

In order to solve the problem of redundancy, the yml file will be more concise.

Four, yml configuration file

​ YAML (YAML Ain't a Markup Language) YAML is not a markup language translated into Chinese is "another markup language", yml is the abbreviation of YAML, usually with the suffix of . A data serialization format recognized by computers and easily read by humans.

4.1 Advantages of yml

1. Higher readability

2. The writing method is more concise

3. More complex data structures can be expressed: arrays, objects...

4. It has better versatility and can be cross-language, not only used in java, but also python, golang... can be used

4.2, yml basic syntax

​yml is a tree-shaped configuration file, and its basic syntax is "key: value". Note that the space between key and value is composed of colon + space, and the space cannot be omitted.

server:
  port: 9999
spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3360/java101
    username: root
    password: 0123456789

Comparison between yml and properties:

insert image description here

4.2.1, yml configures different data types

yml In addition to some prescribed configuration file syntax, others can also be set by yourself.

# 字符串
string:
  value: 你好Spring Boot
# 整数,可以是一级亦可以是二级
int: 100
# 代表 null 的意思,他是有这个值,只不过这个值里面什么都没有
mynull:
  value: ~

4.2.2. Reading of yml configuration file

The way to read the configuration file of yml is also to use @Valueannotations to read, which .propertiesis the same as reading configuration information.

@Controller
@ResponseBody
public class ReadConfigController {
    
    
    @Value("${string.value}")
    private String myString;

    @Value("${int}")
    private int myint;

    @Value("${mynull.value}")
    private Object myNull;

    @RequestMapping("/mynull") // localhost:9999/mynull
    public Object myNull() {
    
    
        return myNull;
    }

    @RequestMapping("/myint") // localhost:9999/myint
    public int getMyint() {
    
    
        return myint;
    }

    @RequestMapping("/mystring")// localhost:9999/mystring
    public String getMyString() {
    
    
        return myString;
    }
}

4.2.3, yml operation object

Write the object into yml:

# 配置对象 写法一:
student:
  id: 1
  age: 18
  name: java
# 写法二:
student2: {
    
     id: 2,age: 20,name: python } # 中间空格是要加上的,一定不能省略

4.2.4, yml read object configuration file

​ When reading an object, you can’t use it @Valueto read it. Logically speaking, you can @Valueread it one by one, but it is obviously impossible to read one by one because there are so many attributes in the general object. You need to create an object A, use @ConfigurationPropertiesto get the data in the configuration file object and inject it into object A.

insert image description here

@ConfigurationPropertiesThe parameter prefix inside is used to select which specific object is used in the configuration file, because there will be multiple objects in the configuration file.

Use the annotation @Component to inject the object into the Spring container, and then use @Autowired/@Resource to read the object in the Spring container, and then you can use the properties in the object.

@Controller
@ResponseBody
@RequestMapping("/stu")
public class StudentController {
    
    

    @Autowired
    private Student student;

    @RequestMapping("/id") // localhost:9999/stu/id
    public int getId() {
    
    
        return student.getId();
    }
}

4.2.5, yml operation array

# 数组 写法一;
listtypes:
  name:
    - java
    - python
    - c++
# 写法二:
listtypes2: {
    
     name: [ php,golang,c# ] }

The space after the "-" in the code cannot be omitted, and the second method of writing is the same.

insert image description here

The above is a pseudocode example, and the attribute names in it must correspond.

4.2.6, yml read array configuration file

The reading of the array is also the same as the reading of the object, using annotations @ConfigurationPropertiesto read, the method steps are the same.

Implementation:

1. Create a list object

@Component
@ConfigurationProperties(prefix = "listtypes") //也是可以直接写成(“listtypes”)
public class ListTypes {
    
    
    List<String> name;

    public List<String> getName() {
    
    
        return name;
    }

    public void setName(List<String> name) {
    
    
        this.name = name;
    }
}

The name here must be consistent with the attribute name in yml, and set cannot be omitted.

2. Inject the list object into the current class and take the properties of the list object.

@Controller
@ResponseBody
@RequestMapping("/listconf")
public class ListConfigController {
    
    

    @Resource
    private ListTypes listTypes;

    @RequestMapping("/getlist") // localhost:9999/listconf/getlist
    public void getList() {
    
    
//        System.out.println(listTypes.getName());
        System.out.println(listTypes.getName().get(0));
    }
}

Here get()is the subscript of the array, you want to get the value in the array to specify the subscript.

4.3, the difference between value plus single and double quotes

mystr:
  value: 你好 \n 世界
  value2: '你好 \n 世界'
  value3: "你好 \n 世界"

image-20230723104953469

From the results of the appeal it can be seen that:

  • By default, strings do not need to add single quotes or double quotes
  • Single quotes escape special characters which end up being just a normal string data
  • Double quotes will not escape the special characters in the string, and the special characters will be used as the meaning they want to express.

Summarize:

  • .properties is a syntax in the form of key-value pairs "key=value". No spaces can be added on both sides of the middle. .yml is configured in a tree-like manner similar to json. The .yml hierarchy uses newline indentation to represent subclasses. It is a grammar in the form of "key: value". Spaces need to be added after the colon, and the spaces cannot be omitted. It is recommended to add a formatting plug-in to reduce the error rate.
  • .properties is the early default configuration file type, but there is some redundancy in the configuration, yml can better solve the redundancy
  • .yml is more versatile and supports more languages. Add a .yml file and save it on the cloud server, and you can use a configuration file as a common configuration file for multiple languages, such as java and Go.
  • .yml can coexist with .properties, but there will be bugs, it is recommended to use the same configuration file type.

Guess you like

Origin blog.csdn.net/qq_54219272/article/details/131878505