Table of contents
1. Introduction to configuration files
5. Read configuration file data
1. Introduction to configuration files
In the SpringBoot project, most configurations have default values, but if you want to replace the default configuration, you can use application.properties or application.yml or application.yaml for configuration. SpringBoot loads application.properties or application.yml files from the resources directory by default. Among them, the application.properties file is a key-value pair type file, which has been used before, so we will not elaborate on the properties file anymore.
If we want to find out how the configuration file overrides the default configuration of the SpringBoot project, then you can check out the following link:
Spring Boot Reference Documentation https://docs.spring.io/spring-boot/docs/2.7.6/reference/htmlsingle/#appendix.application-properties.server In addition to properties files, SpringBoot also supports YAML files for configuration. The extension of a YAML file is .yml or .yaml. Its basic requirements are as follows:
- Case Sensitive
- Use indentation to represent hierarchical relationships
- The same part appears only once
For example, use the properties file to configure the tomcat port:
server.port=8888
And use YAML file to configure tomcat port:
server:
port: 8888
2. Configure simple data
In addition to overriding the default configuration, we can also configure other information in the YAML file for use in our project. Here's how to configure simple data:
grammar:
Data name: value
Example:
name: LYL
Note: There is a space before value
3. Configure object data
grammar:
Object:
attribute name 1: attribute value
attribute name 2: attribute value
# or
object: {attribute name 1: attribute value, attribute name 2: attribute value}
Example:
student:
age: 10
female: male
address: Guangzhou
# 学生2
student2: {sex: male,age: 10,address: Guangzhou}
Note: There is no limit to the number of spaces in front of the attribute name. In YML syntax, the same indentation represents the same level, as long as the number of spaces in front of each attribute is the same.
4. Configure collection data
grammar:
Set:
- value 1
- value 2
# or
set: [value 1, value 2]
Example:
city1:
- Beijing
- Shanghai
- Shenzhen
- Guangzhou#The elements in the collection are objects
students:
- score: 100
name: zhangsan
age: 10
- score: 95
name: lisi
age: 25
- score: 78
name: wangwu
age: 15user:
id: 1001
username: LYL
address:
- Beijing
- Shanghai
- Guangzhou
- Shenzhen
grades:
- subject: math
score: 90
- subject: english
score: 39
5. Read configuration file data
We can map the value in the configuration file to a field of a Spring-managed bean through the @Value annotation. The usage is as follows:
The yml file is as follows:
name: zhangsan
student:
age: 10
female: male
address: Guangzhou
city1:
- Beijing
- Shanghai
- Shenzhen
- Guangzhou
students:
- score: 100
name: zhangsan
age: 10
- score: 95
name: lisi
age: 25
- score: 78
name: wangwu
age: 15
user:
id: 1001
username: LYL
address:
- Beijing
- Shanghai
- Guangzhou
- Shenzhen
grades:
- subject: math
score: 90
- subject: english
score: 39
Read the configuration file:
package com.example.demo.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class YmlController1 {
@Value("${name}")
private String name;
@Value("${students[1].name}")
private String stu_name;
@Value("${city1[3]}")
private String address;
@RequestMapping("/yml1")
@ResponseBody
public String yml1(){
System.out.println(name);
System.out.println(stu_name);
System.out.println(address);
return name+" "+stu_name+" "+address;
}
}
Next we run it to see if we can get the data:
OK, both the console and the web page can successfully read data.
However, it should be noted that @Value can only map simple data types, and cannot map objects and collections in yaml files to attributes.
So how should we map to the entity class? Through @ConfigurationProperties(prefifix="object"), the configuration in the configuration file can be automatically mapped to the entity, so that the object properties configured in the yml file can be directly mapped to the Bean.
OK, let's create a new entity class: Grade, because the User attribute contains this object:
package com.example.demo.pojo;
public class Grade {
private String subject;
private int score;
public Grade(){};
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
@Override
public String toString() {
return "Grade [ " +
"subject='" + subject + '\'' +
", score=" + score +
" ]";
}
}
Then write a control class to read the configuration file:
package com.example.demo.controller;
import com.example.demo.pojo.Grade;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
@Controller
@ConfigurationProperties(prefix = "user")
public class YmlController2 {
private int id;
private String username;
private List<String> address;
private List<Grade> grades;
@RequestMapping("/yml2")
public void yml2(){
System.out.println(id);
System.out.println(username);
System.out.println(address);
System.out.println(grades);
}
@Override
public String toString() {
return "YmlController2 [" +
"id=" + id +
", username='" + username + '\'' +
", address=" + address +
", grades=" + grades +
" ]";
}
public YmlController2() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public List<String> getAddress() {
return address;
}
public void setAddress(List<String> address) {
this.address = address;
}
public List<Grade> getGrades() {
return grades;
}
public void setGrades(List<Grade> grades) {
this.grades = grades;
}
}
Okay, now let's run and see if we can get the data:
OK, successfully printed in the console, indicating that the annotation is effective and can be used.
6. Use of placeholders
The ${} placeholder can be used in YAML files, which has two functions:
Use values from configuration file
For example, we use a custom port and display it on the page: the configuration file is as shown below
Let’s write another controller method
package com.example.demo.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class YmlController3 {
@Value("${myConfig.serverPort}")
private int port;
@RequestMapping("yml3")
@ResponseBody
public String getPort(){
return "你的自定义端口为:"+port;
}
}
Run tests
It can also be injected successfully.
Use the methods provided by the framework
The SpringBoot framework provides some methods for generating random numbers that can be used in yml files:
- ${random.value}: Generate a random number similar to uuid, without "-" connection
- ${random.uuid}: Generate a uuid, connected by a dash
- ${random.int}: Randomly pick a value within the integer range
- ${random.int(10)}: Randomly generate a number within 10
- ${random.int(100,200)}: Randomly generate a number within the range of 100-200
- ${random.long}: Randomly select a value within the long integer range
- ${random.long(100,200)}: Randomly generate a long integer value in the range of 100-200
For example, randomly generate a port 1000-9999: