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