[Spring Boot] Configuration file YML: getting started and using

1.YML configuration file overview

The YML file format is a file format written in YAML (YAML Aint Markup Language). YAML is an intuitive data serialization format that can be recognized by computers, and is easy to be read by humans, easy to interact with script languages, and can be supported YAML library imports different programming language programs, such as: C/C++, Ruby, Python, Java, Perl, C#, PHP, etc. YML files are data-centric and are more concise than the traditional xml method, but the way of describing data is slightly more difficult than xml.
The extension of YML files can be .yml or .yaml. Although the extensions are different, there is no essential difference between the two.

2. Syntax of YML configuration file

  1. Configure normal data (single key value)

Syntax: key: value

Example: There is no space between the key and the colon, but there must be an English half-width space between the value and the space.

# 配置普通数据
name: chenfeilin

  1. Configure object data (the object contains multiple attributes and corresponding values)

Grammar 1
key:
​ key1: value1
​ key2: value2

Example: The number of spaces in front of key1 is not limited. In YML syntax, the same indentation represents the same level, but generally the default is two spaces. The amount of indentation also affects reading.

# 配置对象数据1
person:
  name: feilin
  age: 24

Grammar 2
key: {key1: value1,key2: value2}

Example:

# 配置对象数据2
student: {
    
    name: stu,age: 77}

  1. Configure Map data
    The syntax is the same as above. The above data structure can be parsed as an object or a map collection. No more examples here.

  2. Configure array (List, Set) data

Grammar 1
key:
​ - value1
​ - value2

Example: There is a space between value1 and -

# 配置数组(List、Set)数据1
mylist:
  - chenfeilin
  - 777
  - nagasawa_masami

Grammar 2
key: [value1,value2]

Example:

# 配置数组(List、Set)数据2
city: [beijing,tianjin,shanghai,chongqing]

When the elements in the collection are in the form of objects:

# 集合中的元素是对象形式
users:
  - name: zhangsan
    age: 18
  - name: lisi
    age: 28
  - name: wangwu
    age: 38

3. Annotate @Value to map the properties of the configuration file and configuration class

The @Value annotation is used to map a single key value in the configuration file.
We write a controller and define several properties to receive the values ​​​​in the configuration file:

@RestController
public class TestController {
    
    

    @Value("${name}")
    private String name;

    @Value("${person.name}")
    private String personName;

    @RequestMapping(value = "/getValue")
    public String TestMapping() {
    
    

        System.out.println("name: " + name);
        System.out.println("personName: " + personName);

        return "request OK";
    }

}

Start the project and access http://localhost:8080/getValue
Insert image description here
successfully. Next look at the console: OK
Insert image description here

4. Annotate @ConfigurationProperties configuration mapping

We use the annotation @ConfigurationProperties to complete the mapping of object values ​​in the configuration file to Java configuration objects

The specific method of use is to automatically map the configuration in the configuration file to the entity by annotating @ConfigurationProperties (prefix = "prefix of the key in the configuration file"). For example, person
in the configuration file

person:
  name: feilin
  age: 24

Let’s look at the code:

// 先提供一个载体,用来作为接收对象
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
    
    

    private String name;
    private int age;

    @Override
    public String toString() {
    
    
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

// 然后修改并获取到person
@RestController
public class TestController {
    
    

    @Value("${name}")
    private String name;

    @Autowired
    private Person person;

    @Value("${person.name}")
    private String personName;

    @RequestMapping(value = "/getValue")
    public String TestMapping() {
    
    

        System.out.println("name: " + name);
        System.out.println("person: " + person);
        System.out.println("personName: " + personName);

        return "request OK";
    }

}

There is no problem with the console output:
Insert image description here
it should be noted that the person class must provide get and set methods, otherwise the value in the configuration file will not be obtained. This annotation assigns values ​​to the corresponding attributes through the set method. When we use the @value annotation, we don't need the set method.

We can configure other types, such as collections and array types. Let's modify the configuration file:

person:
  name: feilin
  age: 24
  mylist:
    - chenfeilin
    - 777
    - nagasawa_masami
  address: [beijing,tianjin,shanghai,chongqing]
  girlFriends:
    - girlName: zhangsan
      girlAge: 18
    - girlName: lisi
      girlAge: 28
    - girlName: wangwu
      girlAge: 38

Also modify the configuration class and add another class:

// 添加类gril
public class Girl {
    
    

    private String girlName;
    private int girlAge;

    public String getGirlName() {
    
    
        return girlName;
    }

    public void setGirlName(String girlName) {
    
    
        this.girlName = girlName;
    }

    public int getGirlAge() {
    
    
        return girlAge;
    }

    public void setGirlAge(int girlAge) {
    
    
        this.girlAge = girlAge;
    }

    @Override
    public String toString() {
    
    
        return "Girl{" +
                "girlName='" + girlName + '\'' +
                ", girlAge=" + girlAge +
                '}';
    }
}

// 修改配置类如下
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
    
    

    private String name;
    private int age;
    private List<String> mylist;
    private String[] address;
    private Set<Girl> girlFriends;

    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;
    }

    public List<String> getMylist() {
    
    
        return mylist;
    }

    public void setMylist(List<String> mylist) {
    
    
        this.mylist = mylist;
    }

    public String[] getAddress() {
    
    
        return address;
    }

    public void setAddress(String[] address) {
    
    
        this.address = address;
    }

    public Set<Girl> getGirlFriends() {
    
    
        return girlFriends;
    }

    public void setGirlFriends(Set<Girl> girlFriends) {
    
    
        this.girlFriends = girlFriends;
    }

    @Override
    public String toString() {
    
    
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", mylist=" + mylist +
                ", address=" + Arrays.toString(address) +
                ", girlFriends=" + girlFriends +
                '}';
    }
}

Final console output:

name: chenfeilin
person: Person{name='feilin', age=24, mylist=[chenfeilin, 777, nagasawa_masami], address=[beijing, tianjin, shanghai, chongqing], girlFriends=[Girl{girlName='zhangsan', girlAge=18}, Girl{girlName='lisi', girlAge=28}, Girl{girlName='wangwu', girlAge=38}]}
personName: feilin

If you have multiple yml configuration files, you can distinguish them by annotating @PropertySource when mapping them to the configuration class.
We first create a configuration file, copy the content of person to it, and then add
Insert image description here
specific annotations to the person class. Examples of usage are as follows:

@Component
@ConfigurationProperties(prefix = "person")
@PropertySource(value = {
    
    "classpath:abc.yml"}, factory = YamlPropertySourceFactory.class)
public class Person {
    
    ...}

// 这里需要注解里需要指定一个yaml的加载工厂类,我们可以自己去定义一个:
// 使用的是YamlPropertySourceLoader类的load方法
public class YamlPropertySourceFactory extends DefaultPropertySourceFactory {
    
    

    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
    
    
        if (resource == null) {
    
    
            return super.createPropertySource(name, resource);
        }
        List<PropertySource<?>> sources = new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource());
        return sources.get(0);
    }
}

/**
导的包如下:
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;
*/

The console output remains unchanged:

person: Person{name='feilin', age=24, mylist=[chenfeilin, 777, nagasawa_masami], address=[beijing, tianjin, shanghai, chongqing], girlFriends=[Girl{girlName='zhangsan', girlAge=18 }, Girl{girlName='lisi', girlAge=28}, Girl{girlName='wangwu', girlAge=38}]}

One thing to note here is that the annotation @PropertySource will definitely not report an error without specifying the factory attribute, but it will not be able to load the values ​​​​in our yml configuration file. When the factory attribute is not specified here, it should be used The default loader is installed, but it does not support loading yml files by default, so remember to add this yml file to load the factory class.

5. Query of SpringBoot configuration information

The main purpose of SpringBoot's configuration file is to modify the default configuration information, but it is impossible for us to completely remember all the configuration key values. You can read the documentation when using it. Here is a springboot
[ 2.0.1.RELEASE ] Version's official website configuration document:
Documentation URL:
https://docs.spring.io/spring-boot/docs/2.0.1.RELEASE/reference/htmlsingle/#common-application-properties

6. Code prompts for YML file configuration information

The query of configuration information provided by the official website above helps us to understand the configuration information from scratch. When we master and use some configuration information proficiently, we will definitely write it directly without checking the information. However, due to various insecurities, The reason for the description is that I wrote the wrong ball. At this time, we need some prompt functions to help us retrieve our memory!

There are many blogs introducing this content, and there is no need to write code, and there is no technical content, so I won’t reinvent the wheel. Here is a link to a blog I have seen before: Solving the problem that the idea does not support SpringBoot yml files and the Chinese comments are
garbled
. :
Spring boot application.yml file Chinese comments are garbled

Supplement :
The idea version I am using may be relatively new, and
Insert image description here
the plug-ins used in it may be inconsistent with those in the blog above. Here are the pictures.

Insert image description here

To add :
Sometimes when you create a yml file yourself or use other plug-ins to create a yml file, such as the JBLSpringBootAppGen plug-in, when you just create the file, you will find that there is no prompt in the yml, even if you already have it in the previous project. Tip, there may still be no prompt at this time. You need to rebuild the project before operating the yml file, and then the prompt will take effect. 0.0
Insert image description here

7.YML files are used nested in each other

When the yml file is too long or you want to divide it according to business, you can use the following configuration to introduce split sub-configuration files

Nested single:

spring:
  profiles:
    include:filename

Nest multiple:

spring:
  profiles:
    include:
      - filename1
      - filename2

The name of the sub-configuration file is application-xxx.yml, for example, when nesting a single one: application-filename.yml

8. SpringBoot configures multiple environments corresponding to multiple YML files

Attached are the links:
1. Springboot multi-environment configuration file, how to include multiple yml configuration files? It’s enough to read this article
2. Springboot configures multiple yml files
3. Regarding the related configuration (custom, development, test, official) of SpringBoot’s application.yml switching

Guess you like

Origin blog.csdn.net/cjl836735455/article/details/109370821
Recommended