只需要一个注解就ok:
@ConfigurationProperties("user.other")
“user.other” 这个值匹配的是user下的other对象
yaml :
user:
user-name: addiction
age:19friends:-Smith-Shadow-Kathrin
other:
grand-test: test
color: colorful
price:‘$223‘test:-user-name: addiction
age:19
-user-name: addiction
age:19
-user-other: addiction
age-other: 19other:
test:"this is test"nums:- 1
- 2
- 65
UserProperty类:
其中的属性名要和yml一一对应, grandTest 在 yml 中对应的是 grand-test, 会自动转成驼峰
用 lombok 的 @Data 注解 生成getter/setter, 加上spring 的 @Component 方便 依赖注入
@Data
@Component
@ConfigurationProperties("user.other")public classUserProperty {privateString grandTest;privateString color;privateString price;private List>test;privateOther other; //POJO 类
}
Other 类
@Datapublic classOther {privateString test;private Listnums;
}
测试结果:
测试基类
packagecom.example.demo;importorg.junit.runner.RunWith;importorg.springframework.boot.test.context.SpringBootTest;importorg.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTestpublic classBaseTest {
}
另外还可使用@Value注解修饰属性来获取yaml中的内容:
@Value("${user.other.color}")private String color;