【问题标题】:Using Jaxb2Marshaller with multiple classes having same @XmlRootElement name将 Jaxb2Marshaller 与具有相同 @XmlRootElement 名称的多个类一起使用
【发布时间】:2011-07-07 21:18:08
【问题描述】:

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

控制器代码是这样的,

Source source = new StreamSource(new StringReader(body));
Foo request = (Foo) this.jaxb2Marshaller.unmarshal(source); 

我猜发生这种情况是因为 Bar 有点覆盖 Foo,因为它是在要绑定到 spring-servlet.xml 文件中的类列表中的 Foo 之后编写的

但是,我也有多个使用 @XmlRootElement(name="response") 注释的类,并且编组响应不会产生任何问题。

有没有办法指定 jaxb2Marshaller 用于解组的类?

【问题讨论】:

  • 不,没有办法做到这一点。您需要重构您的设计以使它们彼此区分开来。

标签: spring-mvc jaxb jaxb2


【解决方案1】:

您可以在解组之前将类传递给 Jaxb2Marshaller:

Source source = new StreamSource(new StringReader(body));
jaxb2Marshaller.setMappedClass(Foo.class);

Foo request = (Foo) jaxb2Marshaller.unmarshal(source);

【讨论】:

    【解决方案2】:

    您可以从 Jaxb2Marshaller 创建一个 Unmarshaller,然后您可以将要解组的类作为参数传递给采用 Source 的 unmarshal 方法:

    Source source = new StreamSource(new StringReader(body));
    Unmarshaller unmarshaller = jaxb2Marshaller.createUnmarshaller();
    Foo request = (Foo) unmarshaller.unmarshal(source, Foo.class).getValue(); 
    

    欲了解更多信息,请参阅:

    【讨论】:

      猜你喜欢
      • 2017-02-09
      • 2011-09-16
      • 1970-01-01
      • 1970-01-01
      • 2011-06-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-07
      • 2011-11-20
      相关资源
      最近更新 更多