Search code examples
javaspringvalidationspring-bootjavax

Manually validate with a custom validator without default constructor


I have a custom validation with annotations such as:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = UniquePropertyValidator.class)
public @interface UniqueProperty {

    String message() default "sample message";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

here's my validator:

public class UniquePropertyValidator extends JdbcDaoSupport implements ConstraintValidator<UniqueProperty, UniquePropertyClass> {

    @Inject public UniquePropertyValidator(DataSource dataSource) {
        setDataSource(dataSource);
    }

    @Override
    public void initialize(UniqueProperty property) {

    }

    @Override
    public boolean isValid(UniquePropertyClass propertyClass, ConstraintValidatorContext constraintValidatorContext) { return some boolean; }
}

and I am trying to use it as following:

SpringValidatorAdapter adapter = new SpringValidatorAdapter(validator);
BeanPropertyBindingResult result = new BeanPropertyBindingResult(propertyClass, propertyClass.getClass().getName());
adapter.validate(propertyClass, result, UniquePropertyClass.SomeValidationGroup.class);

if (result.hasErrors())
    throw new MethodArgumentNotValidException(null, result);

however I am getting this error:

HV000064: Unable to instantiate ConstraintValidator: class some.package.UniquePropertyValidator.

Now, I am well aware that my validator class does not have a default constructor without any method parameters. However, the following works with the exact annotation and validator:

public someMethod(@Validated(value = UniquePropertyClass.SomeValidationGroup.class) @RequestBody UniquePropertyClass propertyClass)

What I am asking is; is there a way to manually validate without the default constructor.

P.S. The reason why I cannot use @Validated (the working example above) is:

I have a @PathVariable (say id) and before validating @RequestBody UniquePropertyClass propertyClass object, I need to set the id of UniquePropertyClass object before validating it, since I could not find a way to bind the @PathVariable into @RequestBody field and validate on the fly with @Validated. So giving a hint on how to make this work would also be a perfectly acceptable answer.

Thanks!


Solution

  • Create default constructor for the UniquePropertyValidator and add @Component annotation. Then just add

    @Inject
    private DataSource dataSource;
    

    to inject the datasource rather than init it from Constructor. (See more for autowiring objects in validator)

    UPDATE you can get the bean from context (see Spring get current ApplicationContext )