Yaml configuration injection

SpringBoot uses a global configuration file with a fixed application name

  1. Application. Properties key=value
  2. Application. Yaml syntax structure: key: space value

Yaml syntax

# attribute
name: xiaomi

# object
Teacher:
  name: Teacher Wang
  age: 26

# inline writing of the object
Student: {name: Student Wang.age: 26}

# array
animals:
  - cat
  - pig
  - dog

# inline writing for arrays
Pets: [cat, dog, pig]
Copy the code

Note: YAML’s syntax is strict!

  1. Spaces cannot be omitted
  2. Indent the hierarchy so that any column aligned to the left is of the same hierarchy.
  3. Case sensitivity of attributes and values is very sensitive.

Yaml implements injection configuration files

  1. @ConfigurationProperties(prefix = "people")Implement entity classes andapplication.yamlStudent: Relate.
  2. write@ConfigurationProperties(prefix = "people")There will be red, direct click: the link above to the official website, put the hint to your dependence onpom.xmlCan solve this red, to restart IDEA after the solution

Cat.java

package com.example.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Component
public class Cat {
    private String name;
    private Integer age;
}

Copy the code

People.java

package com.example.pojo;

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

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

@Data
@NoArgsConstructor
@AllArgsConstructor
@Component
@ConfigurationProperties(prefix = "people")
public class People {
    private String name;
    private Integer age;
    private List<Object> hobby;
    private Cat cat;
    private Map<String,Object> maps;
    private boolean happy;
    private Date date;

}
Copy the code

application.yaml

people:
  name: millet
  age: 23
  hobby:
    - music
    - code
    - write
  cat:
    name: Prosperous wealth
    age: 3
  maps: {m1: 1.m2: 2}
  happy: true
  date: 2021/ 4/5
Copy the code

The test class

package com.example;

import com.example.pojo.People;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class Springboot02ConfigApplicationTests {
    
    @Autowired// Inject people
    People people;

    @Test
    void contextLoads(a) { System.out.println(people); }}Copy the code

Running results:

People(name= mi, age=23, hobby=[music, code, write], cat= cat (name= mi, age=3), maps={m1=1, m2=2}, happy=true, date=Mon Apr 05 00:00:00 CST 2021)Copy the code