我已经实现了ConstraintValidator,以便验证包含枚举的DTO。为此,我遵循了this Spring documentation。
这是将应用于枚举字段的自定义注释:
@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:
No validator could be found for constraint 'com.test.ws.web.validation.ValidEnumType' validating type 'com.test.ws.domain.model.Gender'. Check configuration for 'gender'
我正在使用Spring Boot 2.0.4,其中包括用于验证所需的依赖项。
知道为什么会失败吗?
答案 0 :(得分:1)
您的代码中有三个错误。
@Max(100)
不应将此注释应用于字符串字段!仅适用于数字类型。如果需要指定字符串大小范围限制,则可以使用@Size(min = 2, max = 250)
批注。 RequestBody
批注: register(@Valid @RequestBody UserDTO userRegistrationRequest)
我已经为您创建了测试项目。请在此处https://github.com/alex-petrov81/stackoverflow-answers/tree/master/enum-validator
进行检查