SpringBoot環境下 XStream XML與Bean 相互轉換
SpringBoot環境下,XML轉對象時,同一個類無法進行轉換,原因是因爲SpringBoot重新加載了對象;若未指定classloader的時候,SpringBoot未正確使用classloader,需要指定classloader,需要在方法中指定加載的類,添加如下代碼:
xstream.setClassLoader(clazz.getClassLoader());
如:
public static <T> T toBean(Class<T> clazz, String xml) {
try {
XStream xstream = new XStream();
xstream.processAnnotations(clazz);
xstream.autodetectAnnotations(true);
return (T) xstream.fromXML(xml);
} catch (Exception e) {
log.error("[XStream]XML轉對象出錯:{}", e.getCause());
throw new RuntimeException("[XStream]XML轉對象出錯");
}
}
更改爲:
public static <T> T toBean(Class<T> clazz, String xml) {
try {
XStream xstream = new XStream();
xstream.processAnnotations(clazz);
xstream.autodetectAnnotations(true);
xstream.setClassLoader(clazz.getClassLoader());
return (T) xstream.fromXML(xml);
} catch (Exception e) {
log.error("[XStream]XML轉對象出錯:{}", e.getCause());
throw new RuntimeException("[XStream]XML轉對象出錯");
}
}