我已经实现了 ConstraintValidator 以验证包含枚举的 DTO。为此,我遵循了这个 Spring 文档。
这是要应用于枚举字段的自定义注释:
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.CONSTRUCTOR,
ElementType.ANNOTATION_TYPE, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = EnumValidator.class)
public @interface ValidEnum {
String message() default "{com.test.validation.constraints.ValidEnum}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
Class<? extends Enum<?>> target();
}
该EnumValidator如下所示:
public class EnumValidator implements ConstraintValidator<ValidEnum,String> {
private Set<String> enumValues;
@Override
public void initialize(ValidEnum targetEnum) {
Class<? extends Enum> enumSelected = targetEnum.targetClassType();
enumValues = (Set<String>) EnumSet.allOf(enumSelected).stream()
.map(e -> ((Enum<? extends Enum<?>>) e).name()).collect(Collectors
.toSet());
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
return enumValues.contains(value);
}
}
这是枚举:
public enum Gender {
MALE,FEMALE;
}
这是要验证的 DTO:
public final class UserDTO{
@ValidEnum(target = Gender.class)
private Gender gender;
@NotEmpty
@Max(100)
private String fullName;
}
以及验证该字段的控制器:
@Controller
public class RegistrationController {
private static final String REGISTER_USER = "/register";
private final RegistrationService registrationService;
@PostMapping(value = REGISTER_USER)
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
public UserRegistrationResponse register(@Valid UserDTO userRegistrationRequest) {
return registrationService.register(userRegistrationRequest);
}
}
Spring似乎没有检测到验证器,因为它抛出了这个异常:
org.springframework.web.util.NestedServletException: Request processing failed;
nested exception is javax.validation.UnexpectedTypeException: HV000030:
我正在使用 Spring boot 2.0.4,其中包含验证所需的依赖项。
知道为什么会失败吗?
相关分类