Springboot自定义注解校验
自定义注解类
package com.kiet.springboot_project.setting;
import com.kiet.springboot_project.configuration.FlagValidatorClass;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;
/**
* Description: 自定义注解校验
* Author: tianhong yu
* Date: 2018/8/13 10:20
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER,ElementType.FIELD})
@Constraint(validatedBy = FlagValidatorClass.class)
public @interface FlagValidator {
String values();
String message() default "flag不存在";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
配置
public class FlagValidatorClass implements ConstraintValidator<FlagValidator,Object> {
private String values;
@Override
public void initialize(FlagValidator flagValidator) {
this.values = flagValidator.values();
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
String[] value_array = values.split(",");
Boolean isFlag = false;
for (int i = 0; i < value_array.length; i++){
if (value_array[i] .equals(value)){
isFlag = true;
break;
}
}
return isFlag;
}
}
校验
package com.kiet.springboot_project.entity;
import com.kiet.springboot_project.setting.FlagValidator;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.Email;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import java.io.Serializable;
/**
* Description: 数据校验
* Author: tianhong yu
* Date: 2018/8/10 16:54
*/
public class ValidatorEntity implements Serializable {
@NotBlank
@Length(max = 20,min = 2)
private String name;
@Min(value = 1)
private Integer age;
@NotBlank
@Email
private String email;
@FlagValidator(values = "1,2,3")
private String flag ;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFlag() {
return flag;
}
public void setFlag(String flag) {
this.flag = flag;
}
}