【问题标题】:How to do spring bean validations on particular fields for each request如何对每个请求的特定字段进行spring bean验证
【发布时间】:2020-05-22 05:36:57
【问题描述】:

示例:我有 3 种请求格式的付款对象

  1. 请求一张卡付款: 验证卡号、有效期和金额
  2. 代币支付: 代币,到期日
  3. 验证卡: 卡号,有效期

==> 单一支付对象如何实现

【问题讨论】:

    标签: spring spring-security spring-bean


    【解决方案1】:

    您应该使用 ValidationGroups,并注释您想要应用特定验证的对象。

    首先创建验证组(在您的情况下为 3 个):

    public interface CardPayment {
    }
    
    public interface ValidateCard {
    }
    
    public interface TokenPayment {
    }
    

    对 Payment 类应用所需的验证检查(我只包含了@NotNull):

    @Getter @Setter
    public class Payment{
        @NotNull(groups = {CardPayment.class, ValidateCard.class })
        String card_num;
    
        @NotNull(groups = {CardPayment.class, TokenPayment.class, ValidateCard.class})
        Date expire_date;
    
        @NotNull(groups = {TokenPayment.class})
        String token;
    
        @NotNull(groups = {CardPayment.class})
        int amount;
    }
    

    最后激活控制器上的验证(例如卡支付场景):

    @RestController
    public class PaymentController{
        @PostMapping("/payment")
        public ResponseEntity<?> cardPayment(@Validated({CardPayment.class}) @RequestBody Payment payment){
            // logic
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-19
      • 2013-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-12
      • 1970-01-01
      相关资源
      最近更新 更多