@Valid註解詳細解釋及作用

@Valid

用於驗證註解是否符合要求,直接加在變量user之前,在變量中添加驗證信息的要求,當不符合要求時就會在方法中返回message 的錯誤提示信息。

@RestController
@RequestMapping("/user")
public class UserController {
    @PostMapping
    public User create (@Valid @RequestBody User user) {
        System.out.println(user.getId());
        System.out.println(user.getUsername());
        System.out.println(user.getPassword());
        user.setId("1");
        return user;
    }
} 

然後在 User 類中添加驗證信息的要求:

    public class User {
        private String id;  
     
        @NotBlank(message = "密碼不能爲空")
        private String password;
    }

@NotBlank 註解所指的 password 字段,表示驗證密碼不能爲空,如果爲空的話,上面 Controller 中的 create 方法會將message 中的"密碼不能爲空"返回。

當然也可以添加其他驗證信息的要求:

限制  說明
@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格式

除此之外還可以自定義驗證信息的要求,例如下面的 @MyConstraint: 

public class User {
 
    private String id;
 
    @MyConstraint(message = "這是一個測試")
    private String username;
 
}

註解的具體內容:

@Constraint(validatedBy = {MyConstraintValidator.class})
@Target({ELementtype.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyConstraint {
    String message();
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {}; 
}

下面是校驗器:

public class MyConstraintValidator implements ConstraintValidator<MyConstraint, Object> {
    @Autowired
    private UserService userService;
    
    @Override
    public void initialie(@MyConstraint constarintAnnotation) {
        System.out.println("my validator init");
    }
    
    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        userService.getUserByUsername("seina");
        System.out.println("valid");
        return false;
    }
}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章