java—当dto有@notnull时,使用modelmapper进行Map不会引发异常?

jfewjypa  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(463)

我的问题是我有一个名为phonebillpaymentdto的dto,它有一个用@notnull注解的phonenumber字段。当我用modelmapper将这个电话号码为空的dtoMap到phonebillpayment实体时,它不会抛出异常。
当notnull值设置为null时,如何使其抛出异常?
我的课在这里;

public class PhoneBillPaymentTransactionDTO extends PaymentTransactionDTO {

    @NotNull
    private String phoneNumber;

    public PhoneBillPaymentTransactionDTO() {

    }

    public PhoneBillPaymentTransactionDTO(@NotNull BigDecimal amount, @NotNull TransactionTypes type,
            @NotNull String payeeAccountNumber, @NotNull String owner, @NotNull String phoneNumber) {
        super(amount, type, payeeAccountNumber, owner);
        this.phoneNumber = phoneNumber;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

}

控制器:

@PostMapping(path = "/payment/{accountNumber}")
public ResponseEntity<TransactionStatus> payment(@PathVariable String accountNumber,
        @Valid @RequestBody PaymentTransactionDTO paymentTransactionDTO) throws InsufficientBalanceException {

    return new ResponseEntity<>(
            accountService.payment(accountNumber, MapperUtil.createTrxByTrxDTO(paymentTransactionDTO)),
            HttpStatus.OK);
}

Map器工具:

public final class MapperUtil {

    private MapperUtil() {

    }

    private static final ModelMapper mapper = new ModelMapper();

    public static final Transaction createTrxByTrxDTO(TransactionDTO dto) {
        if (dto.getType() == TransactionTypes.DEPOSIT) {
            return mapper.map(dto, DepositTransaction.class);
        }
        if (dto.getType() == TransactionTypes.WITHDRAWAL) {
            return mapper.map(dto, WithdrawalTransaction.class);
        }
        if (dto.getType() == TransactionTypes.PAYMENT) {
            return mapper.map(dto, PaymentTransaction.class);
        }
        if (dto.getType() == TransactionTypes.PHONEBILLPAYMENT) {
            mapper.getConfiguration().setPropertyCondition(Conditions.isNotNull());
            return mapper.map(dto, PhoneBillPaymentTransaction.class);
        }
        throw new UnsupportedTransactionTypeException();
    }

}
oyxsuwqo

oyxsuwqo1#

第一:我非常肯定modelmapper不会做现成的jsr-303注解验证。您需要为生成的bean使用编程验证程序。
但你的方法中更大的问题是:
在你的控制器里 PaymentTransactionDTO . 这可能会被spring验证,但因为spring不知道它实际上可能是什么 PhoneBillPaymentTransactionDTO 因此 phoneNumber -例如-应该验证它只是没有做。
现在,如果您对此进行更多的测试,并记录spring(或jackson)从您的输入中反序列化了哪些内容,那又是什么 PaymentTransactionDTO 对于控制器方法,它能有吗 phoneNumber ? 我打赌你在什么地方配置过 DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES = false 到目前为止,这一切都在起作用。

相关问题