0

I couldn't find anything that helped so im asking:

I have two projects. Project A is the base project that defines basic stuff. Project B is a sub-project of Project A and extends its functionality (Project A should work like a framework and there will be further Projects C and D later). I have a domain object in Project A like:

public class BasePayload {

    @CustomValidator
    private String name;

}

The actual validation of the field 'name' should be in Project B, since all the sub-projects have different valid values for name. Also i would still like to also have a validator in Project A for testing purposes.

@Target({ ElementType.FIELD })
@Retention( RetentionPolicy.RUNTIME )
@Constraint(validatedBy = AbstractFieldValidator.class)
@Documented
public @interface CustomValidator{

    String message() default "message";

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

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

}

I tried defining my own annotation (@CustomValidator) and an abstract validator that has a implementation in Project B. But it doesn't quite work since one can not instantiate the abstract class. Once i have a implementation of that abstract validator in project A, the implementation in Project B is never used.

How would one design this? Is it possible at all? Thank you for your help.

Reborok
  • 25
  • 6
  • This is one of the reasons I don't like java validation specifications. You can use groups [https://stackoverflow.com/questions/35358447/jsr-303-validation-groups-define-a-default-group] But it doesn't preserve the Open-Closed principle. I created a small utility to separate the logic validation from the data: https://github.com/dperezcabrera/validator4j – David Pérez Cabrera Feb 05 '19 at 10:15
  • thank you for your answer. i don't quite understand how groups would help me. Could you maybe tell me a little bit more about what you were thinking? – Reborok Feb 05 '19 at 10:22
  • Read about https://stackoverflow.com/questions/10304100/serviceloader-to-find-implementations-of-an-interface – David Pérez Cabrera Feb 05 '19 at 12:18
  • I'm sorry. I still don't understand how that will help me. Since the validators (extends ConstraintValidator) are found at runtime via reflection I still wouldn't have control over what validator is used, would I? – Reborok Feb 05 '19 at 12:27
  • Inside you can Load dynamically with a serviceLoader and it can be change by another inherit project – David Pérez Cabrera Feb 05 '19 at 13:41
  • So i would create a bean of a serviceloader that finds the right validator-class via an interface. That bean can be overwritten by the sub-project. How would i tell the validation api to use that specific class i found tho? – Reborok Feb 05 '19 at 15:04
  • https://docs.oracle.com/javase/tutorial/ext/basics/spi.html – David Pérez Cabrera Feb 05 '19 at 15:09

0 Answers0