Spring Boot two global configurations and two annotations

1. Overview of global configuration files

The global configuration file can modify some default configuration values. Spring Boot uses an application.properties or application.yaml file as a global configuration file, which is stored in the src/main/resource directory or /config in the class path, and the resource directory is generally selected.

2. Application.properties configuration file

(1) Create Spring Boot’s Web project PropertiesDemo

Create a project using Spring Initializr

After setting the project metadata, click next to enter the next step to add Web and DevTools dependencies

Click the [Create] button to complete the project initialization

Set the project encoding to utf8, click Apply and then Cancel after setting

(2) Add relevant configuration in the application properties file

Click on the resource directory to view the application property configuration file

1. Configure server port number and web virtual path

Configure in the application.properties file

# Set the service port number
server.port=8888
# Set the web virtual path
server.servlet.context-path=/lzy

Start the application and view the console

2. Configuration and use of object types

(1) Create Pet class

Create a bean subpackage in net.wtt.boot, and create a Pet class in the subpackage

package net.wtt.boot.bean;



public class Pet {<!-- -->
    private String type; // type
    private String name; // name

    public String getType() {<!-- -->
        return type;
    }

    public void setType(String type) {<!-- -->
        this.type = type;
    }

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

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

    @Override
    public String toString() {<!-- -->
        return "Pet{" +
                "type='" + type + '\'' +
                ", name='" + name + '\'' +
                '}';
    }
}

(2) Create Person class

Create the Person class in the net.wtt.boot.bean package

package net.wtt.boot.bean;



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


public class Person {<!-- -->
    private int id; // number
    private String name; // name
    private List<String> hobby; // hobby;
    private Map<String, String> family; // family members
    private Pet pet; // pet

    public int getId() {<!-- -->
        return id;
    }

    public void setId(int id) {<!-- -->
        this.id = id;
    }

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

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

    public List<String> getHobby() {<!-- -->
        return hobby;
    }

    public void setHobby(List<String> hobby) {<!-- -->
        this. hobby = hobby;
    }

    public Map<String, String> getFamily() {<!-- -->
        return family;
    }

    public void setFamily(Map<String, String> family) {<!-- -->
        this. family = family;
    }

    public Pet getPet() {<!-- -->
        return pet;
    }

    public void setPet(Pet pet) {<!-- -->
        this. pet = pet;
    }

    @Override
    public String toString() {<!-- -->
        return "Person{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", hobby=" + hobby +
                ", family=" + family +
                ", pet=" + pet +
                '}';
    }
}

(3) Configure the object in the application property file
# configuration object
person.id=1
person.name=Zhang Sanfeng
person.hobby=travel,food,music
person.family.father=Zhang Yunguang
person.family.mother=Wu Wenyan
person.family.grandpa=Zhang Hongyu
person.famliy.grandma=Tang Yuxin
person.family.son=Zhang Junbao
person.family.daughter=Zhang Xiaomin
person.pet.type=Teddy
person.pet.name=Rarity

Configure Person object properties

(4) Add annotations to the Person class

Add the annotation @Component and hand it over to Spring for management

Add annotation @ConfigurationProperties(prefix = “person”)

Note: With the @ConfigurationProperties annotation method, the set method must be used to automatically inject corresponding values for all properties of the Person class, including simple types and complex types

(5) Add annotations to the Pet class

Add the annotation @Component and hand it over to Spring for management
Add annotation @ConfigurationProperties(prefix = “person.pet”) – you don’t need to add

(6) Obtain an instance of the Person class from the Spring container and output it

Implement the interface ApplicationContextAware and implement its abstract method setApplicationContext

Declare the ApplicationContext object and initialize it in setApplicationContext

Create a test method testPerson(), get an instance of the Person class from the Spring container and output

Run the test method testPerson() to view the results

View test class PropertiesDemoApplicationTests code

package net.wtt.boot;

import net.wtt.boot.bean.Person;
import org.junit.jupiter.api.Test;
import org.springframework.beans.BeansException;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

@SpringBootTest
class PropertiesDemoApplicationTests implements ApplicationContextAware {<!-- -->

    private ApplicationContext context; //application container

    @Test
    void contextLoads() {<!-- -->
    }
    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
        throws BeansException{<!-- -->
        context=applicationContext;

    }
    @Test
    public void testPerson(){<!-- -->
        //Get the Person object from the application container by name
        Person person=(Person) context. getBean("person");
        //Output the Person object
        System.out.println(person);
    }

}

(7) Obtain an instance of the Pet class from the Spring container and output it

View the annotations of the Pet class, annotations with configuration properties @ConfigurationProperties(prefix = “person.pet”)

Add the test method testPet() in the test class

Run the test method testPet() to view the results

Comment out the annotation @ConfigurationProperties(prefix = “person.pet”) of the configuration property of the Pet class

Run the test method testPet() again, and check the results to find that the pet’s properties are not injected

Modify application.properties to configure pet objects

As you can see, the properties of the pet object are still not injected. Let’s change the property annotation method and use the @Value annotation method.

Add the value annotation @Valu to the properties of the Pet class

Run the test method testPet() again to see the result

3. Application.yaml configuration file

1. Backup application.properties file

The file is renamed application.back, which means that this file does not work

2. Create the application.yaml file in the resoures directory

Create the application.yaml file
Configure container properties

Configure person object properties

Configure pet object properties

View the contents of the application.yaml file

#configure server
server:
  port: 8888
  servlet:
    context-path: /lzy

#Configure the person object
person:
  id: 1
  name: Zhang Sanfeng
  hobby:
    travel
    gourmet food
    music
  family: {<!-- -->
    father: Zhang Yunguang,
    mother: Wu Wenyan,
    grandpa: Zhang Hongyu,
    grandma: Tang Yuxin,
    son: Zhang Junbao,
    daughter: Zhang Xiaomin
  }
  pet:
    type: teddy dog
    name: Rarity

#Configure the pet object
pet:
  type: teddy dog
  name: Rarity

3. Run the test method testPerson() and view the results

4. Run the test method testPet() and view the results

4. Comparison of two configuration files

1. application.properties configuration file

Using XML syntax, key-value pairs: key=value, no hierarchy
If there are Chinese characters in the value, it must be converted into unicode, otherwise there will be garbled characters

2. application.yaml configuration file

Using YAML syntax, key-value pairs: key: value (there is a space between the colon and the value), with a hierarchical structure
There are Chinese characters in the allowable value, and there is no need to convert them into unicode, and there will be no garbled characters