Validate manually with a custom validator without a default constructor

I have a custom check with annotations like:

@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 like this:

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 an exact annotation and validator:

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

      

What I ask for; there is a way to manually check without default constructor.

PS Reason I can't use @Validated

(working example above):

I have @PathVariable

(say id

) and before validating an object @RequestBody UniquePropertyClass propertyClass

I need to set the object's id

object UniquePropertyClass

before validating it, since I could not find a way to bind @PathVariable

to a field @RequestBody

and validate on the fly with @Validated

. Therefore, giving a hint on how to make this work is also a perfectly acceptable answer.

Thank!

+3


source to share


1 answer


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

@Inject
private DataSource dataSource;

      



to enter the data source, not to create it from the constructor. (For details, see autoincrementing objects in validator )

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

0


source







All Articles