The idea is to use the same annotation for different types, and the logic of the validation depends on the type.
In this way as well as writting a code in this way:
Code:
public class Invoice {
@NotNull @Min(1)
private Integer code;
@NotNull @NotEmpty
private String concept;
@NotNull @Greater(0)
private BigDecimal amount;
@NotNull @Size(min=1)
private Collection<InvoiceDetail> details;
...
}
Also we can writting the code in this simpler way:
Code:
public class Invoice {
@Required
private Integer code;
@Required
private String concept;
@Required
private BigDecimal amount;
@Required
private Collection<InvoiceDetail> details;
...
}
With exactly the same result. This latest way is easier to learn, eaiser to program, and moreover is more configurable.
This polymorphic constraint behaviour can be defined in this way, for example:
Code:
@Documented
@ValidatorClasses({
@ValidatorClass(NotNullConstraint.class),
@ValidatorClass(forType=java.lang.String.class, value=NotEmptyConstraint.class,
@ValidatorClass(forType=java.util.Collection.class, constraint=@Size(min=1),
@ValidatorClass(forType=java.lang.Number.class, constraint=@Greater(0),
})
@Target({METHOD, FIELD})
@Retention(RUNTIME)
public @interface Required {
String message() default "{beancheck.required}";
String[] groups() default {};
}
In fact, OpenXava has a @Required validation annotation:
http://www.gestion400.com/OpenXavaDoc/a ... uired.html
that follows the idea explained here, but configured using XML. In this case, OpenXava/xava/validators.xml, that you can see here:
http://openxava.cvs.sourceforge.net/openxava/OpenXava/xava/validators.xml?view=markup
Also, it would be great a @Required constraint as built-in constraint of JSR-303.
What do you think about "polymorphic constraint" ?
And, about a @Required annotation ?