【问题标题】:Proper way to load properties from XML in Java Spring Boot在 Java Spring Boot 中从 XML 加载属性的正确方法
【发布时间】:2019-04-03 23:01:09
【问题描述】:
我有存储在其中的国家/地区的 XML 文件。每个国家元素都有区域、子区域、国家代码等属性。我有服务应该解析 XML 并根据提供的国家名称获取区域。有什么方法可以将 xml 中的数据加载和使用到内存中,这样我每次想要获取国家/地区的区域时都不需要解析 XML?我不想使用枚举,因为我想拥有可更新的 xml 列表,该列表仅在应用程序启动或第一次使用我的服务时解析一次。因此,在 XML 更新之后,服务器重启就足够了,无需重新构建应用程序来更新枚举。如何实现?
【问题讨论】:
标签:
java
xml
spring-boot
xml-parsing
【解决方案1】:
@chrylis 提出了这个建议 - 我碰巧有一个类似的解决方案,很容易复制/粘贴到一个工作示例中。
如果您的 XML 如下所示:
<countries>
<country name="England" region="Europe"
subregion="Western Europe" countryCode="eng" />
<country name="Scotland" region="Europe"
subregion="West Europe" countryCode="sco" />
</countries>
你有一个Country 这样的类型:
public class Country {
private String name;
private String region;
private String subregion;
private String countryCode;
// getters and setters
}
然后在你的项目中添加以下依赖:
还有这段代码:
public class JacksonXml {
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
InputStream is = JacksonXml.class.getResourceAsStream("/countries.xml");
XmlMapper xmlMapper = new XmlMapper();
List<Country> countries = xmlMapper.readValue(is, new TypeReference<List<Country>>() {
});
Map<String, Country> nameToCountry = countries.stream()
.collect(Collectors.toMap(Country::getName, Function.identity()));
System.out.println(nameToCountry.get("England")
.getRegion());
}
}
将产生:
Europe