引入依赖:
<!--jsr 303--> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.1.0.Final</version> </dependency> <!-- hibernate validator--> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.2.0.Final</version> </dependency>View Code
自定义校验注释:
import javax.validation.Constraint; import javax.validation.Payload; import java.lang.annotation.*; /** * 检查是否属于指定的值 * 例:@TargetValue(values="00,01,02,03,04,05,06,08,13",message="证件类型不正确") */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.PARAMETER,ElementType.FIELD}) @Constraint(validatedBy = TargetValueValidator.class) public @interface TargetValue { //指定的值,多个用,隔开 String values(); //指定提示内容 String message() default ""; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }View Code
import org.apache.commons.lang3.StringUtils; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; /** * 注解@TargetValue实现 */ public class TargetValueValidator implements ConstraintValidator<TargetValue, Object> { private String values; @Override public void initialize(TargetValue targetValue) { this.values = targetValue.values(); } @Override public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) { //允许为空 if (null == value || StringUtils.isBlank(value.toString())) { return true; } String[] valuesArr = values.split(","); if (valuesArr.length == 0) { return false; } for (String str : valuesArr) { if (str.equals(value)) { return true; } } return false; } }View Code
声明:此博客为个人学习之用,如与其他作品雷同,纯属巧合,转载请指明出处!
标签:return,springboot,values,import,validation,javax,String From: https://www.cnblogs.com/zhihuifan10/p/18278356