Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Separate validation annotation and it's validator in separate modules

Situation: you have module with DTO objects used in your API, so that other project(s) can reuse then when sending requests. These DTO classes does have bean-validation annotations in them. And you would like to use your custom validations to validate DTO "arriving" via requests. The sender typically does not validate outgoing data, IIUC, and might not be interested in importing validators along with annotations.

Problem(?): bean-validation is defined in a way, where annotation defines who implements it (which is incorrect and it should be otherwise around imo), with possibility to specify empty array as annotation validator (seems like hack) and then pairing is done via manual hashmap manipulations instead of stuff like service loader etc.

How do you do this?

  • Would you split annotation and it's validator in separate modules?
  • How would you bind them together? I think it should be possible to use {} as validator and then use org.hibernate.validator.internal.metadata.core.ConstraintHelper#putValidatorDescriptors to bind them together, but I did not test it yet + maybe there is better way...
like image 841
Martin Mucha Avatar asked Jul 15 '26 23:07

Martin Mucha


1 Answers

I agree that the annotation defining the validator does feel backwards. While not ideal, I've been able to work around this by separating my custom ConstraintValidator into an interface and implementation.

Example:

In api module define constraint and interface validator

@Constraint(validatedBy = MyConstraintValidator.class)
public @interface MyConstraint
{
}
public interface MyConstraintValidator
    extends ConstraintValidator<MyConstraint, String>
{
}

In your service module define the implementation

public class MyConstraintValidatorImpl implements MyConstraintValidator
{
  private FooService foo;

  @Override
  public boolean isValid( String value, ConstraintValidatorContext ctx)
  {
    // Implement your constraint logic
  }
}
like image 178
CWils Avatar answered Jul 17 '26 13:07

CWils



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!