自定义注解实现@Valid利用枚举检验入参
在实际业务中,会出现,入参会限制传参,比如id ,只能传1,2,通过id来判断业务类型,这时候,传入3就会报错,所以检验id是否在1,2中的逻辑,我们把他简化到入参检验中,也就是@Vaild
引入依赖pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
自定义注解
package com.example.demo0927;
import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.*;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* @author liuxuewei
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD})
@Constraint(validatedBy = EnumValidator.EnumValidatorHandle.class)
public @interface EnumValidator {
Class<?> value();
String message() default "参数错误";
String method() default "getValue";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
class EnumValidatorHandle implements ConstraintValidator<EnumValidator, Object> {
private List<Object> values = new ArrayList<>();
@Override
public void initialize(EnumValidator enumValidator) {
Class<?> clz = enumValidator.value();
Object[] objects = clz.getEnumConstants();
try {
Method method = clz.getMethod(enumValidator.method());
if (Objects.isNull(method)) {
throw new RuntimeException(String.format("枚举对象%s缺少名为%s的方法", clz.getName(), enumValidator.method()));
}
Object value;
for (Object obj : objects) {
value = method.invoke(obj);
values.add(value);
}
} catch (Exception e) {
System.out.println(e.getMessage());
// e.printStackTrace();
}
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
return Objects.isNull(value) || values.contains(value);
}
}
}
枚举类【限制业务类型】
package com.example.demo0927;
import lombok.AllArgsConstructor;
import lombok.Getter;
import java.util.Objects;
/**
* @author liuxuewei
*/
@Getter
@AllArgsConstructor
public enum TestEnum{
TTT(1,"是个1"),
LLL(2,"是个2"),
;
int code;
String dec;
public static String checkCode(int value) { //可以认为是有值,返回一个值,没有就返回null
System.out.println("getValue=>");
for (TestEnum testEnum : TestEnum.values()) {
if (Objects.equals(value, testEnum.getCode())) {
return testEnum.getDec();
}
}
return null;
}
}
入参对象
/**
* @author liuxuewei
*/
@Data
public class TestRequest implements Serializable {
@EnumValidator(value = TestEnum.class, method = "checkCode", message = "id参数有误")
int id;
@NotNull(message = "name不能为空")
String name;
}
controller层
package com.example.demo0927;
import com.alibaba.fastjson.JSON;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author liuxuewei
*/
@RestController
public class NewController {
@RequestMapping("/t")
public String test(@RequestBody @Valid TestRequest request, BindingResult bindingResult){
if (bindingResult.hasErrors()) {
List<ObjectError> allErrors = bindingResult.getAllErrors();
List<String> errMessages = allErrors.stream().map(r -> r.getDefaultMessage()).collect(Collectors.toList());
return errMessages.toString();
}
return JSON.toJSONString(request);
}
}
评论区