知识点:
1、掌握各种数据作为成员变量,配置文件中对应的写法。
需求:创建两个普通类Person、Pet,使Person依赖Pet。绑定配置文件,并把配置文件的数据输出到浏览器。
第一步:创建连个JavaBean类,使用注解 @ConfigurationProperties(prefix = "person") 绑定配置件中的前缀 和 @Component创建对象。
package com.wzy.boot.bean;@ConfigurationProperties(prefix = "person")@Component@ToString@Datapublic 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;}/*=======================================================================*/package com.wzy.boot.bean;@ToString@Datapublic class Pet {private String name;private Double weight;}
第二步:创建 Application.yaml 配置文件,并指定对应胡数据值。
person:#一般成员变量写法userName: 张三boss: falsebirth: 2021/4/10 22:04age: 25# private Pet pet; 依赖类的写法pet:name: 小菊weight: 15.5interests: [Java,看电视]#private List<String> animal;List集合的两种写法,不能混用,混用报错。animal: [gougou,maomao]# - gougou# - maomao# private Map<String, Object> score; Map集合的两种写法,不能混用,混用报错。score: {english: 50,math: 60,chinese: 70}# - english: 50# - math: 60# - chinese: 70#private Set<Double> salarys;Set集合两种写法,不能混用,混用报错。salarys: [2555.0,2888.0,2999.0]# - 2555.0# - 2888.0# - 2999.0#private Map<String, List<Pet>> allPets;两种写法allPets:sick:- {name: 花花,weight: 22.0}- name: 臀臀weight: 18.5health: [{name: 迪迪,weight: 35.5},{name: 美美,weight: 40.5}]# - {name: 小菊,weight: 22.0}# - {name: 玲玲,weight: 22.0}
第三步:创建web层的类 MyController
package com.wzy.boot.controller;
@RestController//
public class MyController {
@Autowired//自动注入
Person person;
@RequestMapping("/person")
public Person person(){
return person;
}
}
第四步:浏览器测试 http://localhost:8888/person
