Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

spring

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 {};
}
like image 731
user123 Avatar asked Jul 30 '18 07:07

user123


1 Answers

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

like image 105
szlik31 Avatar answered Oct 18 '22 20:10

szlik31