user123
user123

Reputation: 577

How to validate @PathVariable with custom validator annotation containing repository bean

I know how to validate @PathVariable from https://stackoverflow.com/a/35404423/4800811 and it worked as expected with standard annotations but not with the customized one using a Repository bean. Maybe the bean is not initialized and I end up with NullPointerException when accessing the end point has @PathVariable validated. So how to get that work?

My Controller:

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

    }
}

My custom validator:

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;
    }

}

My Custom Annotation:

@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 {};
}

Upvotes: 9

Views: 5485

Answers (1)

szlik31
szlik31

Reputation: 43

code in this post is correct, only mistake is that validator need to override initialize method as well. Probably user123 incorrect configure repository bean, the simply way to check this is define it manually in configuration class

Upvotes: 2

Related Questions