【问题标题】:java.lang.ClassCastException: javax.xml.bind.JAXBElement cannot be cast tojava.lang.ClassCastException:javax.xml.bind.JAXBElement 无法转换为
【发布时间】:2016-07-05 10:07:39
【问题描述】:

我正在使用 Spring Boot 来调用 Web 服务。

我的配置类是:

@Configuration
public class ClientAppConfig {
@Bean
public Jaxb2Marshaller marshaller() {
    Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
    marshaller.setPackagesToScan("com.client.stub");
    return marshaller;
}

@Bean
public ARTestClient arTestClient(Jaxb2Marshaller marshaller) {
    ARTestClient client = new ARTestClient();
    client.setDefaultUri("uri");
    client.setMarshaller(marshaller);
    client.setUnmarshaller(marshaller);
   return client;
}

我正在调用服务如下:

    OutputMessageType response = (OutputMessageType) getWebServiceTemplate().marshalSendAndReceive(
            inputMessageType, new SoapActionCallback("http://Serviceuri"));

我收到以下错误:

   [2016-03-18 14:45:43.697] boot - 10272 ERROR [http-nio-8080-exec-1] --- [dispatcherServlet]: Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception 
  [Request processing failed; nested exception is java.lang.ClassCastException: javax.xml.bind.JAXBElement 
  cannot be cast to com.wfs.client.stub.ar.OutputMessageType] with root cause

如何解组来自 web 服务的输出?????? 我如何为响应设置解组器?

【问题讨论】:

    标签: spring jaxb spring-boot unmarshalling


    【解决方案1】:

    有趣的是,我刚刚遇到了同样的问题,这就是我所做的:

    将您的回复投给

    JAXBElement<OutputMessageType>
    

    所以结果是

    JAXBElement<OutputMessageType> response = (JAXBElement<OutputMessageType>) getWebServiceTemplate().marshalSendAndReceive(
            inputMessageType, new SoapActionCallback("http://Serviceuri"));
    // Then just call
    System.out.println(response.getValue());
    

    我的配置和你差不多。我仍在试图弄清楚为什么会有 ClassCastException。至少我们有一个解决方法...

    【讨论】:

    • 那你没有未选中的警告吗?
    • 这是我的问题。我没有在我的 pom.xml 中为我生成的代码指定我的 jaxb lib 版本。 2 年后,我重新生成了我的代码,最新版本的 Jaxb 启动,我的代码给了我这个神秘的错误。谢谢!
    • 谢谢!它确实有帮助
    【解决方案2】:

    如果它今天仍然相关,有一种方法可以在配置文件中解决这个问题。而不是在以下行中使用 .setPackagesToScanmarshaller.setPackagesToScan("com.client.stub")
    考虑使用 .setClassesToBeBound
    但是,您需要引用包下的每个类(将用于编组和解组):

       marshaller.setClassesToBeBound(new Class[] { 
           com.client.stub.Foo.class,
           com.client.stub.Bar.class,
           com.client.stub.Baz.class
       });
    

    无需转换为 JAXBElement。

    【讨论】:

      【解决方案3】:
          JAXBElement<OutputMessageType> response = (JAXBElement<OutputMessageType>) 
          getWebServiceTemplate().marshalSendAndReceive(
          inputMessageType, new SoapActionCallback("http://Serviceuri"));
          // Then just call 
           System.out.println(response.getValue());
      

      对我的情况很有效

      【讨论】:

      • 请在答案中添加更多内容,解释为什么 OP 应该使用您的代码以及它如何解决他们的问题。
      猜你喜欢
      • 1970-01-01
      • 2023-02-02
      • 2016-06-30
      • 2016-01-14
      • 2013-07-25
      • 2017-01-24
      • 2018-08-03
      • 2016-01-07
      • 2015-07-16
      相关资源
      最近更新 更多