只需要一個注解就ok:
@ConfigurationProperties("user.other")
“user.other” 這個值匹配的是user下的other對象
yaml :
yaml 的語法: https://yaml.org/spec/1.2/spec.html#directive//
user: user-name: addiction age: 19 friends: - 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: 19 other: 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 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;