- 使用yaml文件,将默认的application.properties后缀改为yaml
- 导入配置文件处理器
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
- 编写yaml文件
person:
name: zhoutianhao
age: 18
happy: true
birth: 2022/4/15
maps: {k1: v1,k2: v2}
lists:
- music
- basketball
- movies
dog:
name: 旺财
age: 2
- 在SpringBoot的主程序的同级目录下建包,只有这样,主程序才会对这些类生效;建立一个pojo的包,放入Person类和Dog类
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
private String name;
private Integer age;
private Boolean happy;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
}
@Component
public class Dog {
private String name;
private Integer age;
}
- 确认无误后,到测试单元中进行测试,看是否注入成功
@SpringBootTest
class Springboot02ConfigApplicationTests {
@Autowired
private Person person;
@Test
void contextLoads() {
System.out.println(person);
}
}
- 运行结果