10

spring-mvc と Jaxb2Marshaller を使用して Web サービスに取り組んでいます。

2 つのクラスがあり、両方に同じ@XmlRootElement名前の注釈が付けられています

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

}

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

}

3 つのクラス (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); 

spring-servlet.xml ファイルでバインドされるクラスのリストで Foo の後に記述されているため、Bar が Foo をオーバーライドしているため、これが発生していると思います。

ただし、複数のクラスに注釈が付けられて@XmlRootElement(name="response")おり、応答をマーシャリングしても問題はありません。

非整列化のために jaxb2Marshaller が使用するクラスを指定する方法はありますか?

4

2 に答える 2

4

非整列化する前に、クラスを Jaxb2Marshaller に渡すことができます。

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

Foo request = (Foo) jaxb2Marshaller.unmarshal(source);
于 2016-05-13T01:23:52.237 に答える
3

Jaxb2Marshaller から Unmarshaller を作成できます。次に、アンマーシャリングするクラスを、Source を取るアンマーシャリング メソッドにパラメーターとして渡すことができます。

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

詳細については、次を参照してください。

于 2011-03-14T13:10:05.373 に答える