一、导入POM文件

  1. <!--导入配置文件处理器,配置文件进行绑定就会有提示-->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-configuration-processor</artifactId>
  5. <optional>true</optional>
  6. </dependency>
  7. <!--测试所需的依赖-->
  8. <dependency>
  9. <groupId>org.springframework.boot</groupId>
  10. <artifactId>spring-boot-test</artifactId>
  11. <scope>test</scope>
  12. </dependency>
  13. <dependency>
  14. <groupId>junit</groupId>
  15. <artifactId>junit</artifactId>
  16. <scope>test</scope>
  17. </dependency>
  18. <dependency>
  19. <groupId>org.springframework</groupId>
  20. <artifactId>spring-test</artifactId>
  21. <scope>test</scope>
  22. </dependency>

二、Java Bean

  1. /**
  2. * 将配置文件中配置的每一个属性的值,映射到这个组件对应的属性中
  3. * @ConfigurationProperties:告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定
  4. * prefix:说明配置文件中哪个下面的所有属性进行一一映射
  5. *
  6. * 说明:只有Spring容器中的组件才能使用Spring提供的@ConfigurationProperties功能
  7. */
  8. @Component
  9. @ConfigurationProperties(prefix = "staff")
  10. public class Person {
  11. private String name;
  12. private Integer age;
  13. private Boolean boss;
  14. private Date birth;
  15. private Map<String,Object> maps;
  16. private List<Object> lists;
  17. private Dog dog;
  18. // get/set/toString方法省略
  19. }
  20. @Component
  21. public class Dog {
  22. private String name;
  23. private String age;
  24. // get/set/toString方法省略
  25. }

三、配置文件编写

  1. staff:
  2. name: 张三
  3. age: 18
  4. boss: false
  5. birth: 2017/12/12
  6. maps: {province: 江西, city: 赣州}
  7. lists:
  8. - 小明
  9. - 小红
  10. dog:
  11. name: 旺财
  12. age: 2

四、Test 测试Main方法

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootApplicationTest {
    @Autowired
    private Person staff;

    @Test
    public void TestPerson(){
        System.out.println(staff);
    }
}