1. yaml配置文件
注意要将该文件编码格式改为UTF-8
spring:
application:
name: 好好学习
admin:
name: 李斯
age: 24
books:
- name: 数据结构
desc: 数据书
- name: 编译原理
desc: 编译书
2.配置实体类
- @Data设置get,set方法
- @Component注册为Bean
- @ConfigurationProperties(prefix=“”) 设置yaml中对应的内容
- @ToString设置输出格式
@Data
@Component
@ConfigurationProperties(prefix = "admin")
@ToString
public class AdminProperties {
private String name;
private Integer age;
private List<Book> books;
@Data
@ToString
static class Book {
String name;
String desc;
}
}
3.测试
@SpringBootApplication
public class ReadAdminConfigPropertiesApplication implements InitializingBean {
private final AdminProperties adminProperties;
public ReadAdminConfigPropertiesApplication(AdminProperties adminProperties) {
this.adminProperties = adminProperties;
}
public static void main(String[] args) {
SpringApplication.run(ReadAdminConfigPropertiesApplication.class, args);
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println(adminProperties.getName());
System.out.println(adminProperties.getAge());
System.out.println(adminProperties.getBooks());
}
}