SpringBoot global configuration file application.yml

Posted by keyboard on Fri, 07 Feb 2020 14:53:49 +0100

From other frameworks, we have our own configuration files. hibernate has hbm, mybatis has properties, and SpringBoot also has global configuration files.

Spring boot uses a global configuration file, and the name of the configuration file is fixed. (you can start by yourself, but you need to specify application.xxx) there are two types

  • application.properties
  • application.yml 

Function of configuration file: modify the default value of spring boot auto configuration, because spring boot has been auto configured for us at the bottom.

 

YAML

YAML is a recursive abbreviation of "YAML Ain't a Markup Language".

When developing this language, YAML means "Yet Another Markup Language"

YAML A Markup Language: a markup language

YAML isnot Markup Language: not a markup language

Markup Language

Most of the previous configuration files are configured with xml; for example, a simple port configuration, let's compare yaml with xml

yaml configuration:

server: 
    prot: 8080

xml configuration:

<server>
    <port>8081<port>
</server>

xml configures many tags, which is more troublesome than yaml.

YAML syntax

Basic grammar:

k: (space) v   

To represent a pair of key value pairs (spaces cannot be omitted); to control the hierarchical relationship with the indentation of spaces, as long as the left aligned column data is the same level.

Note: the case of attributes and values is very sensitive. Example:

server:
    port: 8081
    path: /hello

Value writing

Literal: normal value [number, Boolean, string]

k: v

Literal quantity can be written directly after it. By default, strings do not need to be enclosed with double quotation marks or single quotation marks;

"" double quotation marks do not escape special characters in the string. Special characters will be used as the meaning they want to express;

For example: name: "kuang \n shen" output: kuang line feed shen

'' single quotation marks will escape special characters, which will eventually be output as normal characters

For example: name: 'kuang \n shen' output: kuang \n shen

Object, Map (key value pair)

k: 
    v1:
    v2:

In the next line, write the attribute and value relationship of the object, and pay attention to indentation; for example:

student:
    name: qinjiang
    age: 3

Inline writing

student: {name: qinjiang,age: 3}

Array (List, set)

Use - values to represent an element in an array, such as:

pets:
 - cat
 - dog
 - pig

Inline writing

pets: [cat,dog,pig]

Program realization

1. If you want to use the properties configuration file, there may be code confusion when importing, you need to adjust it in the IDEA. Here we directly use the yml file to change the default application.properties suffix to yml, as follows

2. Import profile processor

<! -- when importing the profile processor, you will be prompted when binding the profile -- >
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

3. Create a package in the same level directory of the main program of SpringBoot. Only in this way can the main program take effect on these classes. Create a pojo package, a Dog class, and a Person class under com.cc

Class Dog

package com.cc.pojo;

import org.springframework.stereotype.Component;

@Component
public class Dog {
    private String name;
    private Integer age;

    public Dog() {

    }

    public Dog(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

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

Class Person

package com.cc.pojo;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/*
@ConfigurationProperties Effect:
Map the value of each attribute configured in the configuration file to this component;
Tell SpringBoot to bind all the properties in this class with the relevant configuration in the configuration file
 Parameter prefix = "person": all attributes under person in the configuration file are mapped one by one

Only when this component is a component in a container can the @ ConfigurationProperties function provided by the container be used
*/
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
    private String name;
    private Integer age;
    private Map<String, Object> map;
    private List<Object> list;
    private Dog dog;

    public Person() {
    }

    public Person(String name, Integer age, Map<String, Object> map, List<Object> list) {
        this.name = name;
        this.age = age;
        this.map = map;
        this.list = list;
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Map<String, Object> getMap() {
        return map;
    }

    public void setMap(Map<String, Object> map) {
        this.map = map;
    }

    public List<Object> getList() {
        return list;
    }

    public void setList(List<Object> list) {
        this.list = list;
    }

    public Dog getDog() {
        return dog;
    }

    public void setDog(Dog dog) {
        this.dog = dog;
    }

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

4. Write the yml configuration file (pay attention to the syntax structure)

person:
  name: Boss
  age: 3
  map: {k1: v1,k2: v2}
  list:
    - code
    - music
    - girl
  dog:
    name: Small black
    age: 3

5. After confirmation, test in the test unit to see if the injection is successful!

package com.cc;

import com.cc.pojo.Dog;
import com.cc.pojo.Person;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import javax.xml.ws.soap.Addressing;

@SpringBootTest
class Springboot02ConfigApplicationTests {

    @Autowired
    private Person person;

    @Test
    void contextLoads() {

        System.out.println(person);
    }

}

 

Operation result

 

In addition to yml, the configuration file also has properties that we used before. We didn't say that when the properties configuration file is written in Chinese, there will be garbled code. We need to set the encoding format to UTF-8 in IDEA;

Settings - > fileencodings;

In addition, our class is directly related to the configuration file. We use the @ configurationProperties method. Another way is to use @ value

@Component //Registered bean
public class Person {
    //Use @ value directly
    @Value("${person.name}") //Take value from configuration file
    private String name;
    @Value("#{11*2}")  //#{SPEL} Spring expression
    private Integer age;
    @Value("true")  // Literal
    private Boolean happy;
    
    . . . . . .   
}

The results are still obtainable.

This is not friendly to use! We need to annotate and assign each attribute separately, which is troublesome; let's look at a function comparison chart

  • cp only needs to be written once, and value needs to be added to each field
  • Loose binding: what does this mean? For example, the last name written in my yml, which is the same as the last name, - the following letters are capitalized by default. This is loose binding
  • JSR303 data validation. This is that we can add a layer of filter validation in the field to ensure the validity of the data
  • Complex type encapsulation. Objects can be encapsulated in yml, which is not supported with @ value

Conclusion:

  • Values can be obtained by configuring both yml and properties. yml is highly recommended
  • If we only need to get a value in the configuration file in a business, we can use @ value
  • If we specially write a JavaBean to map with the configuration file, we will directly use @ configurationProperties. Don't hesitate!

 

 

Published 198 original articles, won praise 11, visited 10000+
Private letter follow

Topics: Spring xml SpringBoot Attribute