只需要一个注解就ok:
@ConfigurationProperties("user.other")
“user.other” 这个值匹配的是user下的other对象
yaml :
yaml 的语法: https://yaml.org/spec/1.2/spec.html#directive//
user:
user-name: addiction
age:
friends:
- Smith
- Shadow
- Kathrin
other:
grand-test: test
color: colorful
price: '$223'
test:
-
user-name: addiction
age:
-
user-name: addiction
age:
-
user-other: addiction
age-other:
other:
test: "this is test"
nums:
-
-
-
UserProperty类:
其中的属性名要和yml一一对应, grandTest 在 yml 中对应的是 grand-test, 会自动转成驼峰
用 lombok 的 @Data 注解 生成getter/setter, 加上spring 的 @Component 方便 依赖注入
@Data
@Component
@ConfigurationProperties("user.other")
public class UserProperty {
private String grandTest;
private String color;
private String price; private List<Map<String, Object>> test; private Other other; //POJO 类
}
Other 类
@Data
public class Other { private String test; private List<Integer> nums;
}
测试结果:
测试基类
package com.example.demo; import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class)
@SpringBootTest
public class BaseTest {
}
另外还可使用@Value注解修饰属性来获取yaml中的内容:
@Value("${user.other.color}")
private String color;