前言:
首先,接口参数校验应该都不陌生,大部分应该都会借助javax.validation进行快捷校验,一般都是在入参字段上添加@NotNull、@NotEmpty等,对于一些特殊的入参校验逻辑,可能不是很适用,现在介绍一下自定义注解方式。
依赖:
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.10.Final</version>
</dependency>
代码:
自定义注解:
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = {EnumValidator.class})
public @interface EnumValid {
String message() default "";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
/**
* 目标枚举类
*/
Class<? extends Enum> target() default Enum.class;
}
实际校验类:
import com.honor.wpshowdemo.serverone.valid.EnumValid;
import org.apache.commons.lang.StringUtils;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
public class EnumValidator implements ConstraintValidator<EnumValid, Object> {
private EnumValid annotation;
@Override
public void initialize(EnumValid constraintAnnotation) {
annotation = constraintAnnotation;
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
boolean result = false;
Class<?> cls = annotation.target();
// target为枚举,并且value有值,才进行校验
if (cls.isEnum() && (value != null)) {
Object[] objects = cls.getEnumConstants();
for (Object obj : objects) {
//object类型转map
Class<?> jqlEnum = obj.getClass();
Field[] fs = jqlEnum.getDeclaredFields();
Map<String, String> objMap = new HashMap<>();
for (Field f : fs) {
f.setAccessible(true);
try {
objMap.put(f.getName(), f.get(obj).toString());
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
}
if (objMap.get("code") != null && StringUtils.equals(objMap.get("code"), String.valueOf(value))) {
result = true;
break;
}
}
}
return result;
}
}
测试:
测试代码:
import lombok.Getter;
public enum TestEnum {
FAILED(0),
SUCCESS(1)
;
@Getter
private Integer id;
TestEnum(Integer id) {
this.id = id;
}
}
import lombok.Data;
@Data
public class TestRequest {
@EnumValid(target = TestEnum.class, message = "id不符合要求")
private Integer id;
}
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
@RestController
public class TestController {
@PostMapping("/test")
public void test(@RequestBody @Valid TestRequest testRequest) {
}
}
测试结果如下:
至此结束,欢迎指正。