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转对象出错");}}