Spring Boot自定义约束验证组件

问题描述 投票:0回答:2

配置类

@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 不调用自定义验证器吗?

java spring javax.validation
2个回答
2
投票

我在

src/main/resources/META-INF/services
中创建了一个名为
javax.validation.ConstraintValidator
的文件,其中包含一个列表新行,其中分隔了您创建的自定义约束验证器的所有限定名称。

这样,Spring 将自动注册自定义验证器。

此文件将从 Spring 自动检查并包含到构建的工件中。

应用此方案后请注意注释配置。您应该用

@Constraint(validatedBy = { })
进行注释,以防止双重验证器初始化。


0
投票

以下几点可以帮助澄清问题。

  • @Component
    类不需要
    UniqueLoginValidator
    注释。
  • 为了清晰起见并确保正确的方法重写,建议在
    @Override
    方法上使用
    isValid
    注释。
  • 建议在
    ElementType.PARAMETER
    方法中使用
    RestController
    进行验证,因为它可以提高清晰度并确保注释直接应用于方法参数。

enter image description here

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.