配置类
@ComponentScan(basePackages = {"validator"})
class AppConfiguration { ... }
注释类
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = UniqueLoginValidator.class)
public @interface UniqueLogin {
String message() default "{com.dolszewski.blog.UniqueLogin.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
验证器类
@Component
class UniqueLoginValidator implements ConstraintValidator<UniqueLogin, String> {
private UserRepository userRepository;
public UniqueLoginValidator(UserRepository userRepository) {
this.userRepository = userRepository;
}
public void initialize(UniqueLogin constraint) {
}
public boolean isValid(String login, ConstraintValidatorContext context) {
return login != null && !userRepository.findByLogin(login).isPresent();
}
}
我有一个带有属性
@UniqueLogin String login
的类,我还使用其他注释,如 @Size
和 @Max
,最后 2 个有效,但我的自定义注释不起作用。
您能帮忙理解为什么 spring 不调用自定义验证器吗?
我在
src/main/resources/META-INF/services
中创建了一个名为 javax.validation.ConstraintValidator
的文件,其中包含一个列表新行,其中分隔了您创建的自定义约束验证器的所有限定名称。
这样,Spring 将自动注册自定义验证器。
此文件将从 Spring 自动检查并包含到构建的工件中。
应用此方案后请注意注释配置。您应该用
@Constraint(validatedBy = { })
进行注释,以防止双重验证器初始化。