首页 > 解决方案 > JAXB 无法将值转换为 BigDecimal

问题描述

在 Spring Boot 应用程序中,我使用maven-jaxb2-plugin从 WSDL 文件生成类:

<plugin>
                <groupId>org.jvnet.jaxb2.maven2</groupId>
                <artifactId>maven-jaxb2-plugin</artifactId>
                <version>0.14.0</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <schemaLanguage>AUTODETECT</schemaLanguage>
                    <schemaDirectory>src/main/resources</schemaDirectory>
                    <schemaIncludes>
                        <include>*.wsdl</include>
                    </schemaIncludes>
                    <generatePackage>pl.pantuptus.app.integration</generatePackage>
                </configuration>
            </plugin>

WSDL 文件包含定义为的销售字段:

<s:element minOccurs="1" maxOccurs="1"
                        name="sales" type="s:decimal" />

它由maven-jaxb2-plugin转换为生成类的 BigDecimal 属性:

@XmlElement(name = "sales", required = true)
protected BigDecimal sales;

我在配置组件中显式配置 JAXB Marshaller:

@Configuration
public class IntegrationConfig {
    @Bean
    public Jaxb2Marshaller marshaller() {
        Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
        marshaller.setContextPath("pl.pantuptus.app.integration");
        return marshaller;
    }

    @Bean
    public MyClient myClient(Jaxb2Marshaller marshaller) {
        MyClient client = new MyClient();
        client.setDefaultUri("http://localhost:8080/ws");
        client.setMarshaller(marshaller);
        client.setUnmarshaller(marshaller);
        return client;
    }
}

我的问题是当我从客户端调用 WS 端点时:

getWebServiceTemplate().marshalSendAndReceive(url, request)

我收到一个销售属性值为空的对象。

我的猜测是 JAXB 无法正确解析此属性,因为它在响应中具有基于逗号的格式。

<sales>23 771,08</sales>

问题来了:我如何告诉 Jaxb2Marshaller(或任何其他 Marshaller 实现)如何将此类字符串转换为 BigDecimal?

标签: javaspringspring-bootjaxb

解决方案


IntegrationConfig中将验证器添加到编组器后:

marshaller.setValidationEventHandler(new MyValidationEventHandler());

我发现 SOAP 文档(在销售值中带有逗号)没有针对 WSDL 进行验证:

iswlMyValidationEventHandler:链接异常:java.lang.NumberFormatException

我认为唯一的解决方案是请求正确的 WSDL 文件或对服务提供者的正确 WS 响应。


推荐阅读