我知道如何从https://stackoverflow.com/a/35404423/4800811验证@PathVariable
并且它可以与标准注释一起使用,但不能与使用Repository bean的定制注释一起使用。也许bean没有初始化,并且在访问端点NullPointerException
时,我最终以@PathVariable
结束。那么如何获得这项工作呢?
我的控制器:
@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 {};
}
答案 0 :(得分:1)
代码是正确的,唯一的错误是验证者也需要重写initialize方法。可能是user123不正确的配置存储库bean,检查它的简单方法是在配置类中手动定义它