spring-mvc - 将 Jaxb2Marshaller 与具有相同 @XmlRootElement 名称的多个类一起使用

标签 spring-mvc jaxb jaxb2

我正在使用 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/

相关文章:

Spring MVC 3.0 : How do I bind to a persistent object

rest - 什么是 jaxb 提供程序、jaxb 处理程序和 contextResolvers?

java - 包级别的 XmlJavaTypeAdapter 不起作用

JAXB 按原样使用 String

java - 如何获取类型 ="xs:date"而不是类型 ="xs:dateTime"

java - Spring Hibernate 获取选中的列

java - 如何限制独立执行且可通过Web应用程序执行的可运行JAR的执行。?

javax.xml.bind.UnmarshalException : XML document structures must start and end within the same entity

java - JAXB和enum实现接口(interface)

java - org.springframework.beans.factory.BeanInitializationException : Could not load properties