一、导入POM文件
<!--导入配置文件处理器,配置文件进行绑定就会有提示-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!--测试所需的依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
二、Java Bean
/**
* 将配置文件中配置的每一个属性的值,映射到这个组件对应的属性中
* @ConfigurationProperties:告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定
* prefix:说明配置文件中哪个下面的所有属性进行一一映射
*
* 说明:只有Spring容器中的组件才能使用Spring提供的@ConfigurationProperties功能
*/
@Component
@ConfigurationProperties(prefix = "staff")
public class Person {
private String name;
private Integer age;
private Boolean boss;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
// get/set/toString方法省略
}
@Component
public class Dog {
private String name;
private String age;
// get/set/toString方法省略
}
三、配置文件编写
staff:
name: 张三
age: 18
boss: false
birth: 2017/12/12
maps: {province: 江西, city: 赣州}
lists:
- 小明
- 小红
dog:
name: 旺财
age: 2
四、Test 测试Main方法
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootApplicationTest {
@Autowired
private Person staff;
@Test
public void TestPerson(){
System.out.println(staff);
}
}