import com.ess.news.commons.validation.validators.FixedValueValidator;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* 固定值
* @author kangyu
* @date 11:47 2020/5/14
*/
@Documented
@Constraint(validatedBy = FixedValueValidator.class)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RUNTIME)
public @interface FixedValueValidation {
String message() default "参数值不对";
String[] value();
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RUNTIME)
@Documented
@interface List {
FixedValueValidation[] value();
}
}
import com.ess.news.commons.validation.constraints.FixedValueValidation;
import org.springframework.util.StringUtils;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;
public class FixedValueValidator implements ConstraintValidator<FixedValueValidation, String> {
private String[] starts;
@Override
public void initialize(FixedValueValidation constraintAnnotation) {
starts = constraintAnnotation.value();
}
/**
* 支持正则匹配
* @author kangyu
* @date 13:59 2020/5/14
* @param value,context
* @return boolean
*/
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (!StringUtils.isEmpty(value)) {
for (int i = 0; i < starts.length; i++) {
if (Pattern.matches(starts[i], value)) {
return true;
}
}
}
return false;
}
}
使用:
方法上:
实体类:
over…