【发布时间】:2017-11-16 19:45:59
【问题描述】:
我正在尝试使用 spring boot 和 @ConfigurationProperties 注释将带有复杂键的映射从 spring yaml 配置文件解组到 java.util.Map。有很多关于带有简单键的地图的例子,比如
map:
key: value
甚至是带有简单键和复杂值的映射,例如
map:
key: {firstPartOfComplexValue: alpha, secondPartOfComplexValue: beta}
我已经测试了上述两个示例 - 效果很好。
现在我需要一个复杂的地图键:
map:
? {firstPartOfAKey: someValue1, secondPartOfAKey: someValue2}: value
这种解组的结果是一张空地图。 请你告诉我我做错了什么 提前致谢
这是我的代码:
application.yml
custom:
users:
? {firstPartOfAKey: hello, secondPartOfAKey: world} : tom
bean 解组
@Component
@ConfigurationProperties("custom")
public class MyBean {
private Map<Key, String> users = new HashMap<>();
public Map<Key, String> getUsers() {
return users;
}
public void setUsers(Map<Key, String> users) {
this.users = users;
}
@Override
public String toString() {
return users.toString();
}
public static class Key {
private String firstPartOfAKey;
private String secondPartOfAKey;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Key key = (Key) o;
return Objects.equals(firstPartOfAKey, key.firstPartOfAKey) &&
Objects.equals(secondPartOfAKey, key.secondPartOfAKey);
}
@Override
public int hashCode() {
return Objects.hash(firstPartOfAKey, secondPartOfAKey);
}
public String getFirstPartOfAKey() {
return firstPartOfAKey;
}
public void setFirstPartOfAKey(String firstPartOfAKey) {
this.firstPartOfAKey = firstPartOfAKey;
}
public String getSecondPartOfAKey() {
return secondPartOfAKey;
}
public void setSecondPartOfAKey(String secondPartOfAKey) {
this.secondPartOfAKey = secondPartOfAKey;
}
@Override
public String toString() {
return String.format("firsPartOfKey: '%s', secondPartOfKey: '%s'", firstPartOfAKey, secondPartOfAKey);
}
}
}
java 配置(它是空的)
@Configuration
@ComponentScan(basePackages = {"com"})
@EnableAutoConfiguration
@EnableConfigurationProperties
public class Config {
}
单元测试
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {Config.class})
public class TestProps {
@Autowired
private MyBean myBean;
@Test
public void testYamlPropsLoad() {
System.out.println(myBean);
}
}
测试仅对具有复杂键的地图打印“{}”。其他地图(带有简单键)运行良好。
【问题讨论】:
标签: java spring spring-boot