Source code based on SpringBoot 2.4.4

1. Know the configuration file

1.1 Loading configuration Files

When a SpringBoot project is created, an application.properties file is automatically created, which is the default SpringBoot configuration file.

Properties files and application.yaml files will be found and loaded by default when SpringBoot is started in the following path:

(1) The classpath directory

(2) Config folder in the classpath directory

(3) Project root directory

(4) Subfolders of config folder under the root directory of the project

(5) Config folder under the root directory of the project

The priority goes from high to low, and the last loaded overrides the first loaded.

IO /spring-boot…

1.2 Configuration file Types

(1) Application. Properties

(2) Yaml suffix: application

1.3 Comparison of two Configuration files

  • Custom Properties profiles can be loaded using the @propertysource annotation, but custom YAML files cannot be loaded.
  • Configuration file loading order: YAML, YML, XML, Properties (later loaded will overwrite the previous loaded)

2. Yaml configuration file

2.1 introduction

YAML is a recursive abbreviation of “YAML Ain’t Markup Language” (YAML is not a Markup Language). At the time the Language was developed, YAML actually meant: “Yet Another Markup Language”.

Ideal for data-centric configuration files

2.2 Basic Syntax

(1) Key: value. There must be a space between the colon and value.

(2) case-sensitive.

(3) Use indentation to represent hierarchy.

(4) Indent does not allow the use of TAB, only space.

(5) The number of Spaces indented does not matter, as long as elements of the same level are left aligned.

(6) #

(7) The string does not need to be quoted. “Will escape. For example, ‘\n’ prints \n, but “\n” prints newlines.

2.3 Data Types

(1) Literals: single, non-divisible values. Date, Boolean, string, number, null

k: v
Copy the code

(2) Object: a collection of key-value pairs. Map, Hash, set, and Object

# inline
k: {k1:v1.k2:v2.k3:v3}
# or
k: 
  k1: v1
  k2: v2
  k3: v3
Copy the code

(3) Array: A set of values arranged in order. Array, list, queue

# inline
k: [v1.v2.v3]
# or
k:
 - v1
 - v2
 - v3
Copy the code

2.4 instance

Define two entity classes Person and Pet, and bind the attributes of the Person class to the configuration file

@Data
@ConfigurationProperties(prefix = "my-person")
@Component
public class Person {
    private String userName;
    private Boolean boss;
    private Date birth;
    private Integer age;
    private Pet pet;
    private String[] interests;
    private List<String> animal;
    private Map<String, Object> score;
    private Set<Double> salarys;
    private Map<String, List<Pet>> allPets;
}

@Data
public class Pet {
    private String name;
    private Double weight;
}
Copy the code

Configure the Person properties in the YAML file

my-person:
  user-name: CodeTiger
  boss: true
  birth: 1996/ 11/29
  Random can be used to generate various types of random values
  age: ${random.int}
  pet:
    name: tomcat
    weight: 100
  interests: [basketball.football]
  animal:
    - jerry
    - tom
  score:
    english:
      first: 30
      second: 40
      third: 50
    math: [131.140.148]
    chinese: {first: 128.second: 136}
    salarys: [3999.4999.98.5999.99]
    allPets:
      sick:
        - {name: tom}
        - {name: jerry.weight: 47}
      health: [{name: mario.weight: 47}]
Copy the code

Start SpringBoot and you can print out the property values of the Person entity class. If you configure some field values for Person in application.properties, how will they be loaded?

my-person.interests=basketball, football, pingpang
my-person.user-name=lxp
my-person.score.chinese=100
my-person.score.english=99
Copy the code

Start SpringBoot and print the Person

Person(userName=lxp, boss=true, birth=Fri Nov 29 00:00:00 CST 1996, age=16165848, pet=Pet(name=tomcat, weight=100.0), interests=[basketball, football, pingpang], animal=[jerry, tom], score={english=99, chinese=100, math={0=131.1=140.2=148}}, salarys=[3999.0.4999.98.5999.99], allPets={sick=[Pet(name=tom, weight=null), Pet(name=jerry, weight=47.0)], health=[Pet(name=mario, weight=47.0)]})
Copy the code

Properties overrides the properties configured in application.yaml, and if the property has more than one field, it is merged. For example, score={English =99, Chinese =100, math={0=131, 1=140, 2=148}} is the result of combining two configuration files.

2.5 Enabling Automatic Prompt

When our class and profile properties are bound, there is no automatic prompt to set property discovery in the profile. When we annotate the class with the @ConfigurationProperties Annotation, IDEA prompts us to configure the Annotation Processor

Docs. Spring. IO/spring – the boot…

According to the documentation, we just need to add the relevant JAR package to pom.xml.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>
Copy the code

At packaging time, we don’t need to put it into the JAR package, so remove

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <excludes>
                    <exclude>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-configuration-processor</artifactId>
                    </exclude>
                </excludes>
            </configuration>
        </plugin>
    </plugins>
</build>
Copy the code

3. Use YAML to implement multi-environment configuration

We can write the configuration of multiple environments in one file, which can be separated by symbols, as shown in the application.yaml file

spring:
  profiles:
  	Use the configuration of the development environment
    active: dev
---
Configure the development environment
server:
  port: 8888
spring:
  profiles: dev
---
Production environment configuration
server:
  port: 8888
spring:
  profiles: prod
Copy the code

Yml and application-prod.yml, respectively, represent the configuration in the development environment and the configuration in the production environment.

You can then specify which configuration file to use in the application.yaml file.

We can also specify which environment configuration to use by specifying in our code

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;

@SpringBootApplication
public class TestApplication {

    public static void main(String[] args) {
        SpringApplicationBuilder builder = new SpringApplicationBuilder(TestApplication.class);
        builder.application().setAdditionalProfiles("dev"); builder.run(args); }}Copy the code

It can also be specified when the JAR package is launched using a command

java -jar xxx.jar --spring.profiles.active=dev
Copy the code