@RequestMapping("/argValid")
@RestController
public class NotNullValidTestController {
/**null,empty,blank,customiseArg
* {
* "id": "",
* "name": " ",
* "bookId": "1"
* "no":"no"
* }*/
@PostMapping("/deliverArgJson")
public ValidTestNotNullDto executedPost(@Valid @RequestBody ValidTestNotNullDto dto) {
String upperId = dto.getId().toUpperCase();
ValidTestNotNullDto validTestNotNullDto = new ValidTestNotNullDto();
validTestNotNullDto.setId(upperId);
BeanUtil.copyProperties(dto,validTestNotNullDto);
return validTestNotNullDto;
}
}
arg
@Data
class ValidTestNotNullDto {
@NotNull(message = "Id为null")
private String id;
@NotEmpty(message = "name is empty")
private String name;
@NotBlank(message = "bookId is blank")
private String bookId;
@MyConstraint(message = "no is no")
private String no;
}
自定义注解接口
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Constraint(validatedBy = {MyConstraintValidator.class})
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyConstraint {
String message();
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
实现
class MyConstraintValidator implements ConstraintValidator<MyConstraint, Object> {
@Override
public void initialize(MyConstraint constraintAnnotation) {
System.out.println("my validator init");
}
@Override
public boolean isValid(Object o, ConstraintValidatorContext constraintValidatorContext) {
boolean judge = "no".equals(o);
System.out.println("valid");
return judge;
}
}