【问题标题】:How to validate @PathVariable with custom validator annotation containing repository bean如何使用包含存储库 bean 的自定义验证器注释来验证 @PathVariable
【发布时间】:2019-01-06 09:38:27
【问题描述】:

我知道如何从https://stackoverflow.com/a/35404423/4800811 验证@PathVariable 并且它使用标准注释按预期工作,但不能使用使用 Repository bean 的自定义注释。也许 bean 没有初始化,当访问端点有 @PathVariable 验证时,我最终得到 NullPointerException。那么如何完成这项工作呢?

我的控制器:

@RestController
@Validated
public class CustomerGroupController {
    @PutMapping(value = "/deactive/{id}")
    public HttpEntity<UpdateResult> deactive(@PathVariable @CustomerGroupEmpty String id) {

    }
}

我的自定义验证器:

public class CustomerGroupEmptyValidator implements ConstraintValidator<CustomerGroupEmpty, String>{
    @Autowired
    private CustomerRepository repository;

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        // NullPointerException here (repository == null)
        if (value!=null && !repository.existsByCustomerGroup(value)) {
            return false;
        }
        return true;
    }

}

我的自定义注释:

@Documented
@Constraint(validatedBy = CustomerGroupEmptyValidator.class)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomerGroupEmpty {
    String message() default "The customer group is not empty.";
    Class<?>[] groups() default {};
    Class<? extends Payload> [] payload() default {};
}

【问题讨论】:

标签: java spring


【解决方案1】:

这篇文章中的代码是正确的,唯一的错误是验证器也需要覆盖初始化方法。可能是 user123 错误配置存储库 bean,检查它的简单方法是在配置类中手动定义它

【讨论】:

    猜你喜欢
    • 2022-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-13
    • 1970-01-01
    • 2011-12-24
    相关资源
    最近更新 更多