https://www.cnblogs.com/houchen/p/13128563.html
1、导入依赖
<!--导入配置文件处理器 配置文件进行绑定就会有提示-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
<!--spring boot 的单元测试 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
2、创建要进行属性注入的配置类
package com.atguigu.controller.bean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
/**
* @author houChen
* @date 2020/6/14 22:36
* @Description:
*/
/**
* ConfigurationProperties:
* 将配置文件中每一个属性的值,都映射到这个组件中
* @ConfigurationProperties : 告诉SpringBoot将本类中的所有属性 和配置文件中相关的配置进行绑定
* prefix = "person" ==》指定类中的属性和配置文件中哪个下面的属性进行一一配置
*
* 配置类必须是容器中的组件
*/
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
private String lastName;
private Integer age;
private Boolean boss;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
@Override
public String toString() {
return "Person{" +
"lastName='" + lastName + '\\\\'' +
", age=" + age +
", boss=" + boss +
", maps=" + maps +
", lists=" + lists +
", dog=" + dog +
'}';
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Boolean getBoss() {
return boss;
}
public void setBoss(Boolean boss) {
this.boss = boss;
}
public Map<String, Object> getMaps() {
return maps;
}
public void setMaps(Map<String, Object> maps) {
this.maps = maps;
}
public List<Object> getLists() {
return lists;
}
public void setLists(List<Object> lists) {
this.lists = lists;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
}
package com.atguigu.controller.bean;
/**
* @author houChen
* @date 2020/6/14 22:38
* @Description:
*/
public class Dog {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
3、在yml中编写配置
person:
last-name: zhangsan
age: 19
boss: false
birth: 2018/12/12
maps: {k1: v1,k2: v2}
lists:
- lisi
- wangwu
dog:
name: uzi
age: 20
4、在Person类上,按住 ctrl+shift+t ==> 快速创建 Person的测试类
/**
* @author houChen
* @date 2020/6/14 23:36
* @Description: Spring Boot的单元测试
*
* 可以在测试期间很方便的 类似编码一样进行自动注入等功能
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonTest {
@Autowired
Person person;
@Test
public void testPerson(){
System.out.println(person);
}
}
5、结果