Spring Boot Learning 1.2 - yml configuration file and read

SpringBoot support configuration and operation of the acquired data in yml file inside, there are a pair of files in yml key (key: value) data relationships.

First, create a file named application yml in the resource path of the project file the following figure:

       We can then configure the server port number yml file inside:

server:
  port: 8000

Bean and then create a folder in the main folder, create classes and Teacher Student class:

  The following code written in the Student class, set properties

@Component
@ConfigurationProperties(prefix = "student")
public class Student {
    private String Name;
    private Integer age;
    private Boolean pass;
    private Date birth;

    private Map<String,Object> maps;
    private List<Object> lists;
    private Teacher teacher;

Use @Component annotation indicates that this is a component, use ConfigurationProperties (prefix = "student") for dynamic binding component, prefix = "student" statement indicates that all profiles following attribute mapping, the configuration of each attribute file value mapped to the component, and then use the alt + insert disposed setter and getter methods and toString () method. Results are as follows:

, Then write the code inside the class Teacher, no comment, but the need to set the getter and getter methods and toSting () all the properties by the above method.
public class Teacher {
    private String name;
    private int age;
    private String level;
    private String sex;

Add the following dependencies in pom.xml file, import the configuration file processor, and then re-run springboot project will be executed successfully

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

Then writes the data in the file yml, providing component read:

student:
    Name: 窃格瓦拉
    age: 21
    pass: true
    birth: 1998/09/02 18:00:00
    maps: {k1 : v1,k2 : v2}
    lists:
      - 林欢
      - 蔡女士
    teacher:
      name: 超威男猫
      age: 30
      level: 叫兽
      sex: ♂

Test file in the main program is then test directory, a spring boot unit test, Student class is instantiated, the component obtained from the data of the print file yml

@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {

    @Autowired
    Student student;

    @Test
    public void contextLoads() {
        System.out.println(student);
    }

}

Click the Start button in the file test output results are as follows:

Published 58 original articles · won praise 31 · views 40000 +

Guess you like

Origin blog.csdn.net/qq_37504771/article/details/95248036