Spring @Valid的两种用法

首先
限制 说明

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Null   限制只能为null
@NotNull    限制必须不为null
@AssertFalse    限制必须为false
@AssertTrue 限制必须为true
@DecimalMax(value)  限制必须为一个不大于指定值的数字
@DecimalMin(value)  限制必须为一个不小于指定值的数字
@Digits(integer,fraction)   限制必须为一个小数,且整数部分的位数不能超过integer,小数部分的位数不能超过fraction
@Future 限制必须是一个将来的日期
@Max(value) 限制必须为一个不大于指定值的数字
@Min(value) 限制必须为一个不小于指定值的数字
@Past   限制必须是一个过去的日期
@Pattern(value) 限制必须符合指定的正则表达式
@Size(max,min)  限制字符长度必须在min到max之间
@Past   验证注解的元素值(日期类型)比当前时间早
@NotEmpty   验证注解的元素值不为null且不为空(字符串长度不为0、集合大小不为0)
@NotBlank   验证注解的元素值不为空(不为null、去除首位空格后长度为0),不同于@NotEmpty,@NotBlank只应用于字符串且在比较时会去除字符串的空格
@Email  验证注解的元素值是Email,也可以通过正则表达式和flag指定自定义的email格式

对应得实体类假设为

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
public class AAA  {

    @Pattern(
            regexp = "^(Draft|Active|Inactive)$",
            message = "Please input valid action, only Draft|Active|Inactive " + "is allowed")
    private String action;

    @Pattern(regexp = "^.{0,100}$", message = "Product name only allows 1-100 characters")
    private String productName;

    @Pattern(regexp = "^.{0,500}$", message = "Product description only allows 1-500 characters")
    private String description;

 
    private String startDate;

   
    private String endDate;

    @Pattern(
            regexp = "^(Day|Week|Month|Year)$",
            message = "Please input valid termUnit, only Day|Week|Month|Year is " + "allowed")
    private String termUnit;

    @Pattern(regexp = "(\\d)?", message = "Please input valid termValue, termValue only allows 1 digits")
    private String termValue;

    @Pattern(
            regexp = "^(\\d){0,18}$",
            message = "Please input valid counterLimit, counterLimit only allows 1-18 " + "digits")
    private String counterLimit;

    @Pattern(regexp = "^(\\d){0,18}$", message = "Please input valid minLimit, minLimit only allows 1-18 digits")
    private String minLimit;

    @Pattern(regexp = "^(\\d){0,18}$", message = "Please input valid maxLimit, maxLimit only allows 1-18 digits")
    private String maxLimit;

    @Pattern(
            regexp = "^(Day|Week|Month|Year|Times)$",
            message = "Please input valid rolloverPeriodUnit, only " + "Day|Week|Month|Year|Times is allowed")
    private String rolloverPeriodUnit;

    @Pattern(
            regexp = "^(\\d){0,3}$",
            message = "Please input valid rolloverPeriodValue, rolloverPeriodValue only " + "allows 1-3 digits")
    private String rolloverPeriodValue;

    @Pattern(
            regexp = "^(\\d){0,3}$",
            message = "Please input valid maxNumberOfRollover, rolloverPeriodValue only " + "allows 1-3 digits")
    private String maxNumberOfRollover;

    @Pattern(
            regexp = "^(.){0,18}$",
            message = "Please input valid fundsLenderId, fundsLenderId only allows 1-18 " + "characters")
    private String fundsLenderId;

    @Pattern(
            regexp = "^(\\d){0,3}$",
            message = "Please input valid daysToWatch, daysToWatch only allows 1-3 " + "digits")
    private String daysToWatch;

    @Pattern(regexp = "^(\\d){0,3}$", message = "Please input valid daysToLost, daysToLost only allows 1-3 digits")
    private String daysToSubstandard;

    @Pattern(regexp = "^(\\d){0,3}$", message = "Please input valid daysToLost, daysToLost only allows 1-3 digits")
    private String daysToLost;

    @Pattern(regexp = "^(\\d){0,3}$", message = "Please input valid daysToBad, daysToBad only allows 1-3 digits")
    private String daysToBad;

    private String loanType;


    @Pattern(regexp = "^(1000|5000)$", message = "Please input valid availableIdentityType, only 1000|5000 is allowed")
    private String availableIdentityType;

    @Pattern(
            regexp = "^(.){0,10}$",
            message =
                    "Please input valid currencyInMultiplesOf, currencyInMultiplesOf only allows 1-10 " + "characters")
    private String currencyInMultiplesOf;

    @Pattern(regexp = "^(.){0,10}$", message = "Please input valid strategyId, strategyId only allows 1-10 characters")
    private String strategyId;

    @Pattern(
            regexp = "^(Weekly|Monthly|Maturity)$",
            message = "Please input valid repaymentFrequency, only " + "Weekly|Monthly|Maturity is allowed")
    private String repaymentFrequency;

    @Pattern(
            regexp = "^(\\d){0,3}$",
            message = "Please input valid repaymentDay, repaymentDay only allows 1-3 " + "digits")
    private String repaymentDay;

    @Pattern(regexp = "^(F|G|M|S)$", message = "Please input valid repaymentScheduleType, only F|G|M|S is allowed")
    private String repaymentScheduleType;

    @Pattern(regexp = "^(Y|N)$", message = "Please input valid supportInstallment, only Y|N is allowed")
    private String supportInstallment;

    @Pattern(regexp = "^(Y|N)$", message = "Please input valid supportAutoRepayment, only Y|N is allowed")
    private String supportAutoRepayment;

    @Pattern(regexp = "^(Y|N)$", message = "Please input valid allowRepayInAdvance, only Y|N is allowed")
    private String allowRepayInAdvance;

    @Pattern(
            regexp = "^(\\d){0,3}$",
            message = "Please input valid statementDaysBeforDue, statementDaysBeforDue only allows 1-3" + " digits")
    private String statementDaysBeforDue;

    @Pattern(regexp = "^(Y|N)$", message = "Please input valid autoChangeRiskCategory, only Y|N is allowed")
    private String autoChangeRiskCategory;

 
    @Pattern(regexp = "^(Y|N)$", message = "Please input valid deductAccessFee, only Y|N is allowed")
    private String deductAccessFee;

 
    @Pattern(
            regexp = "^(All|Same|Unlimited)$",
            message = "Please input valid rejectWhenOverdue, only " + "All|Same|Unlimited is allowed")
    private String rejectWhenOverdue;

   
}

第一种一般在controller入口接收参数加上@Valid
如:

1
2
3
4
5
6
7
8
  @ApiOperation(value = "/v1/aa", notes = "Modify product info")
    @PostMapping(value = "/v1/aa/{productId}")
    @ResponseBody
    public JsonObject modifyProduct(
            @RequestBody @Valid ModifyProductInfoRequest request,
            @PathVariable(name = "productId") Long productId,
            @org.springframework.web.bind.annotation.RequestHeader(value = "X-Operator-ID", required = false)
                    String operatorID)

如果此时有不满足条件得会报错

第二种:
如果想在业务中来校验,这样方便于记录日志或者错误原因或者做其他操作得话,可以在对应得service中建一个类似如下得空实现方法

1
2
3
service A{
    public void validateRequest(@Valid AAA  requestData) {}
    }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
service b{
@Resource
service A a;
   public void doSomeThing( AAA  requestData) {
   .....
  try {
           // 使用正则表达式校验数据格式
           a.validateRequest(requestData);
       } catch (ConstraintViolationException e) {
           Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
           for (ConstraintViolation<?> violation : constraintViolations) {
               String path = violation.getPropertyPath().toString();
               throw new Exception("xxxxxxxx");
           }
       }
   ....

}
   }

这样来处理,一定要通过对象.方法来调用,类似 a.validateRequest(requestData);否则不会促发触发Spring Validation校验