如何在 Spring Web 应用程序中使用 FastMoney?

问题描述 投票:0回答:1

我正在使用 Spring Web 创建一个虚拟存款表格。应该是这样,在处理金钱时想尝试 JavaMoney API。所以,

@RequestBody
DTO 是这样的:

@Data
@Builder
@RequiredArgsConstructor
public class PaymentDto {
    private String recipientName;
    @JsonInclude
    private FastMoney amount;
}

我从邮递员发布的 JSON 有

{"amount": 100.00} //also tried with "100.00"

我得到的错误是

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `org.javamoney.moneta.FastMoney` (no Creators, like default constructor, exist): no int/Int-argument constructor/factory method to deserialize from Number value (100)
     at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 2, column: 15] (through reference chain: com.blah.PaymentDto["amount"])

Documentation 说 FastMoney 可以通过多种方式创建,静态构造函数就是其中之一。但这种方式使我必须使用一定数量的货币,这是我想避免的。我也许可以在请求中设置区域设置,但那是另一次了。

FastMoney m = FastMoney.of(200.20, "美元");

我在 google 上找到的 examples 来自 11 年前 - 所以我假设 JavaMoney 可能不是涉及支付的典型 Web 应用程序的正确 API。因此,我将投入一些时间来了解是否有其他 API 可以简化资金的使用。 同时,我仍然想了解人们实际上如何使用 JavaMoney - 因为我无法弄清楚

FastMoney
如何使用 lombok 工作。

Lombok提供了

staticConstructor
,但它们适用于类,而不是类中的字段。

 @Data(staticConstructor="of")
  public static class Exercise<T> 

所以问题是:

  • 如何使用 Lombok 设置
    FastMoney
    字段?
  • 如何转换 (thymeleaf 到 spring 控制器)将表单值提交给
    FastMoney
spring-boot lombok java-money
1个回答
0
投票

我相信解决您的问题的正确方法不是依赖 Lombok 构造函数,而是实现自定义 Jackson 反序列化器。

参见例如

@JsonComponent
public class FastMoneyDeserializer extends JsonDeserializer<FastMoney> {
    @Override
    public FastMoney deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        Integer amount = jsonParser.getIntValue();
        return FastMoney.of(amount, "USD");
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.