2011-03-03 124 views
10

我正在使用spring-mvc和Jaxb2Marshaller进行Web服务。使用Jaxb2Marshaller与具有相同@XmlRootElement名称的多个类

我有两个类,都具有相同@XmlRootElement

@XmlRootElement(name="request") 
class Foo extends AstractRequest { 

} 

@XmlRootElement(name="request") 
class Bar extends AbstractRequest { 

} 

所有三类(AbstractRequest,富,酒吧)都包含在同一顺序

现在请求classesToBeBound列表注释使用Bar的工作正常。但随着消息Bar cannot be cast to Foo

控制器代码是这样解组期间使用美孚的一个抛出一个ClassCastException例外,

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

我想 发生这种情况,因为酒吧是那种因为它是后写覆盖的Foo在Spring-servlet.xml文件中要绑定的类列表中的Foo

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

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

+2

不,没有办法做到这一点。你需要重构你的设计,以保持彼此不同。 – skaffman 2011-03-03 13:15:30

回答

3

您可以从Jaxb2Marshaller创建的Unmarshaller,那么你可以通过你想要解组作为参数,需要一个源解组方法的类:

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

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

4

您可以通过类来Jaxb2Marshaller前解组:

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

Foo request = (Foo) jaxb2Marshaller.unmarshal(source); 
相关问题