yaml configuration and application of SpringBoot

environmental problems:

  1. There will be problems between Junit5 and idea versions in SpringBoot unit test, so unit test cannot be performed!
    Solution: add the dependency in pom.xml file.
<dependency>
    <groupId>org.junit.platform</groupId>
    <artifactId>junit-platform-launcher</artifactId>
    <version>1.5.2</version>
</dependency>
  1. In order to prevent the annotation of @ ConfigurationProperties from being red in the idea, you need to import dependencies!
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>

3.JSR303 data verification requires import dependencies!

<dependency><!--Data verification dependency, in order to achieve@Email annotation-->
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

1.banner modifies the startup pattern of SpringBoot

Create a banner.txt file in the resources directory

(¸¸.♥➷♥•*¨)¸.•´¸.•*¨) ¸.•*¨)                               
(¸.•´(¸. ¸.•´¸.•*¨) ¸.♥➷•*¨)                               
─▀██▀─▄███▄─▀██─██▀██▀▀▀█─                                 
──██─███─███─██─██─██▄█──conquers                    
──██─▀██▄██▀─▀█▄█▀─██▀█──all ♥➷♥                         
─▄██▄▄█▀▀▀─────▀──▄██▄▄▄█                                  
¸.•´¸.•*¨) ¸♥.•*¨) (¸.•´¸♥➷♥¸.•´♥¸.•´♥¸.•*¨)♥.•*¨)¸.•*♥¸ 

You can modify the pattern display when SpringBoot starts

2.yaml(yml) file

Note: strict grammar requirements!

  1. Spaces cannot be omitted
  2. Indentation is used to control the hierarchical relationship. As long as a column of data aligned on the left is at the same level.
  3. Attributes and values are case sensitive.

example:

  1. Create an entity class
package com.chen.pojo;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Component/*Equivalent to < bean id = ""... > class injection function*/
@ConfigurationProperties(prefix = "person")
public class Person {

    private String name;
    private Integer age;
    private Boolean happy;
    private Date birth;
    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog;

    public Person() {
    }

    public Person(String name, Integer age, Boolean happy, Date birth, Map<String, Object> maps, List<Object> lists, Dog dog) {
        this.name = name;
        this.age = age;
        this.happy = happy;
        this.birth = birth;
        this.maps = maps;
        this.lists = lists;
        this.dog = dog;
    }

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

    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 Boolean getHappy() {
        return happy;
    }

    public void setHappy(Boolean happy) {
        this.happy = happy;
    }

    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }

    public Map<String, Object> getMaps() {
        return maps;
    }

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

    public List<Object> getLists() {
        return lists;
    }

    public void setLists(List<Object> lists) {
        this.lists = lists;
    }

    public Dog getDog() {
        return dog;
    }

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

  1. Create an application.yaml file in the resources directory
person:
  name: cjs${random.uuid}
  age: ${random.int}
  happy: false
  birth: 2021/11/6
  maps: {k1: v1,k2: v2}
  lists:
    -code
    -music
    -girl
  dog:
    name: ${person.name:chen}_cjs
    age: 5
  1. Automatically assemble the entity class in the default test class and test the results
package com.chen;

import com.chen.pojo.Dog;


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

@SpringBootTest
class Springboot02ConfigApplicationTests {
    @Autowired/*Spring Auto assemble objects*/
    private Person person;
    @Test
    void contextLoads() {
        System.out.println(person);
    }



}

It can be found that the data in the yml file can be assigned to the corresponding attributes of the object.
@The annotation ConfigurationProperties(prefix = "person") binds the class to yml
The value of prefix should correspond to the instantiated parameter name!

Differences between yaml and properties configuration files:

  1. @ConfigurationProperties only needs to be written once, and @ Value needs to be added to each field.
  2. Loose binding: what does that mean? For example, the last name written in my yml is the same as lastName, and the letters followed are capitalized by default. This is loose binding. You can test it
  3. JSR303 data verification, that is, we can add a layer of filter verification in the field to ensure the legitimacy of the data.
  4. Complex type encapsulation. Objects can be encapsulated in yml, but value is not supported.

Conclusion: the values can be obtained by configuring yml and configuring properties, and yml is strongly recommended;
If we only need to obtain a value in the configuration file in a business, we can use @ value;
If we specially write a JavaBean to map one by one with the configuration file, we can directly @ configurationProperties. Don't hesitate!

3. Data verification of jsr303

Create an entity class:

package com.chen.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.*;
import java.util.Date;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Component
@Validated/*This annotation must be opened before the data verification of JSR303 can be performed*/
@ConfigurationProperties(prefix = "user")
public class TestUser {
    @NotNull(message = "Name cannot be empty")
    private String username;
    @Max(value = 120,message = "How old you are")
    private int age;
    @Email(message = "Mailbox format error")
    private String email;
    @Past(message = "Incorrect birthday input")
    private Date birth;

}

Create the corresponding yml file:

user:
  username: cjs
  age: 100
  email: 1983691635@qq.com
  birth: 2000/12/25

Test class:

package com.chen;

import com.chen.pojo.Dog;


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

@SpringBootTest
class Springboot02ConfigApplicationTests {
    @Autowired/*Spring Auto assemble objects*/
    private TestUser user;
    @Test
    void contextLoads() {
        System.out.println(user);
    }



}

It can be seen that the data verification of JSR303 is used to verify the data in the entity class.
Note: the @ Validated annotation must be added to the entity class to enable data verification.

4. Multi environment switching

profile is Spring's support for different configuration functions for different environments. You can quickly switch environments by activating different environment versions.

Create yaml file:

server:
  port: 8082
#Select the environment block to activate
spring:
  profiles:
    active: dev

---

server:
  port: 8083
spring:
  profiles: dev

---
server:
  port: 8084
spring:
  profiles: test

---

Run the SpringBoot main program and find that the port number has changed.

Conclusion: you can modify the port number of SpringBoot by modifying the value in active,
Similarly, in development, we can use this way to modify the program environment!

5. Configuration file loading location

Priority 1: config folder configuration file under project path
Priority 2: configuration file under project path
Priority 3: config folder configuration file under resource path
Priority 4: configuration file under resource path

Posted on Sat, 06 Nov 2021 17:12:54 -0400 by matanoosh