我想將我的Spring引導應用程序中的yml文件映射到帶有String Key和PromotionPolicy值的HashMap,並使用默認的spring引導實現來解析值,但PromotionPolicy對象只包含當我嘗試從Map讀取值時,所有實例的默認值[0,false,false]。將yaml映射到SpringBoot中的對象hashmap
我陽明是:
promotionPolicies :
policies:
P001NN:
PromotionPolicy:
expiryPeriodInDays: 16
reusable: true
resetExpiry: false
P001YN:
PromotionPolicy:
expiryPeriodInDays:1
reusable:true
resetExpiry:false
P001NY:
PromotionPolicy:
expiryPeriodInDays:1
reusable:false
resetExpiry:true
我的型號是:
public class PromotionPolicy {
private int expiryPeriodInDays;
private boolean reusable;
private boolean resetExpiry;
public int getExpiryPeriodInDays() {
return expiryPeriodInDays;
}
public void setExpiryPeriodInDays(int expiryPeriodInDays) {
this.expiryPeriodInDays = expiryPeriodInDays;
}
public boolean isReusable() {
return reusable;
}
public void setReusable(boolean reusable) {
this.reusable = reusable;
}
public boolean isResetExpiry() {
return resetExpiry;
}
public void setResetExpiry(boolean resetExpiry) {
this.resetExpiry = resetExpiry;
}
}
組件Java類,如下:
@Configuration
@ConfigurationProperties(prefix = "promotionPolicies")
@EnableConfigurationProperties
@Component
public class PromotionPolicyConfig {
private Map<String, PromotionPolicy> policies = new HashMap<String, PromotionPolicy>();
public void setPolicies(Map<String, PromotionPolicy> policies) {
this.policies = policies;
}
public Map<String, PromotionPolicy> getPolicies() {
return policies;
}
}
想在這裏顯示的值:
@RestController
@RequestMapping("/test")
public class LoyaltyServiceController {
@Autowired
PromotionPolicyConfig promotionPolicyConfig;
@RequestMapping(value = "/try")
public String tryThis() {
for (Entry<String, PromotionPolicy> entry : promotionPolicyConfig.getPolicies().entrySet()) {
System.out.print(entry.getKey() + " : ");
System.out.print(entry.getValue() + " : ");
System.out.print(entry.getValue().getExpiryPeriodInDays() + " : ");
System.out.print(entry.getValue().isResetExpiry() + " : ");
System.out.println(entry.getValue().isReusable() + " : ");
}
}
我的輸出是如下:
P001NN : [email protected] : 0 : false : false :
P001YN : [email protected] : 0 : false : false :
P001NY : [email protected] : 0 : false : false :
,而我希望的結果包含在我的陽明的值。 我也試過在我的yml中刪除行「PromotionPolicy:」,但沒有運氣。
請求幫助瞭解如何將yml映射到自定義對象的地圖。
可能是這將有助於 http://stackoverflow.com/questions/32593014/mapping-list-in-yaml-to-list-of-objects-in-春季啓動 – pvpkiran