SpringBoot中的Validated注解及其自定义约束:
SpringBoot Validator 如果不生效,可能是缺少了依赖引入,一定要在Pom.xml中,添加下面的依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
例如,实现一个start & end date的约束,约束POJO类中,Start <= End date,否则报错。
首先定义一个 Interface注解类:
然后,实现约束类的实现代码,此处没有用反射,而是用BeanUtils来获取属性数据,更安全可靠一点。
最后,使用的时候,在数据POJO类使用即可:
如果要让Controller中RequestParam 参数生效,必须在类上使用 @Validated 注解,否则方法名中的 @Min, @Max, 等注解不会生效,如下:
- @RestController
- @Validated
- @RequestMapping("/data")
- public class DataController {
- @GetMapping("/query")
- public ResponseEntity<APIResult<Object>> query(@RequestParam
- @Max(value = 100) @Min(value = -1)
- @Digits(message = "ID must be int", fraction = 0, integer = 10)
- @NotEmpty(message = "id is required")
- String id) {
- return ResponseEntity.ok().body(APIResult.ok(id));
- }
- }
如果不加 @Validated,上述代码中下划线的不会不会生效,切记。
枚举约束:
Enum.java
- import javax.validation.Constraint;
- import javax.validation.Payload;
- import java.lang.annotation.Documented;
- import java.lang.annotation.Retention;
- import java.lang.annotation.RetentionPolicy;
- import java.lang.annotation.Target;
- import static java.lang.annotation.ElementType.*;
- @Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
- @Retention(RetentionPolicy.RUNTIME)
- @Documented
- @Constraint(validatedBy = EnumConstraintValidator.class)
- public @interface Enum {
- String message() default "Invalid enum value";
- Class<?>[] groups() default {};
- Class<? extends Payload>[] payload() default {};
- Class<? extends java.lang.Enum<?>> clazz();
- }
EnumConstraintValidator.java
- import javax.validation.ConstraintValidator;
- import javax.validation.ConstraintValidatorContext;
- import java.util.Arrays;
- import java.util.List;
- import java.util.stream.Collectors;
- public class EnumConstraintValidator implements ConstraintValidator<Enum, java.lang.Enum<?>> {
- private List<String> valueList;
- @Override
- public void initialize(Enum constraintAnnotation) {
- valueList = Arrays.stream(constraintAnnotation.clazz().getEnumConstants())
- .map(e -> e.name().toUpperCase()).collect(Collectors.toList());
- }
- @Override
- public boolean isValid(java.lang.Enum<?> value, ConstraintValidatorContext constraintValidatorContext) {
- return value == null || valueList.contains(value.name().toUpperCase());
- }
- }
使用:
@Enum(message = "Wrong value", clazz = Type.class, groups = ValidGroups.Query.class)
private Type type;