我正在使用 spring-mvc 和 Jaxb2Marshaller 开发 Web 服务。
我有两个类,都用相同的 @XmlRootElement
注释姓名
@XmlRootElement(name="request")
class Foo extends AstractRequest {
}
@XmlRootElement(name="request")
class Bar extends AbstractRequest {
}
所有三个类(AbstractRequest、Foo、Bar)都以相同的顺序包含在 classesToBeBound 列表中
现在使用 Bar 的请求工作正常。但是使用 Foo 的那个在解码过程中会抛出 ClassCastException 异常,并带有消息
Bar cannot be cast to Foo
Controller 代码是这样的,
Source source = new StreamSource(new StringReader(body));
Foo request = (Foo) this.jaxb2Marshaller.unmarshal(source);
我猜这是因为 Bar 是一种覆盖 Foo 的原因,因为它是在要绑定(bind)到 spring-servlet.xml 文件中的类列表中的 Foo 之后编写的
但是,我也有多个用
@XmlRootElement(name="response")
注释的类并且编码响应没有任何问题。有没有办法指定 jaxb2Marshaller 用于解码的类?
最佳答案
您可以在解码之前将类传递给 Jaxb2Marshaller:
Source source = new StreamSource(new StringReader(body));
jaxb2Marshaller.setMappedClass(Foo.class);
Foo request = (Foo) jaxb2Marshaller.unmarshal(source);
关于spring-mvc - 将 Jaxb2Marshaller 与具有相同 @XmlRootElement 名称的多个类一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5178251/