I'm wondering whether it's possible to register new constraint validator of some custom type to a annotation defined by Bean Validation specification. For example, let's image I have a class that accumulates several int values
public class IntContainer
{
private int value1;
private int value2;
public int getValue1()
{
return value1;
}
public void setValue1(final int value1)
{
this.value1 = value1;
}
public int getValue2()
{
return value2;
}
public void setValue2(final int value2)
{
this.value2 = value2;
}
}
I would like to register a custom constraint validator to support the @Positive annotation for this type (instead of created a custom annotation).
public class PositiveIntContainerValidator implements ConstraintValidator<Positive, IntContainer>
{
@Override
public boolean isValid(final IntContainer value, final ConstraintValidatorContext context)
{
//TODO: do some validation here based on IntContainer state
return false;
}
}
So that later I can use this:
@Positive
private IntContainer valueContainer;
The @NotNull annotation is, actually, an explicit contract declaring that: A method should not return null. Variables (fields, local variables, and parameters) cannot hold a null value.
The Bean Validation model is supported by constraints in the form of annotations placed on a field, method, or class of a JavaBeans component, such as a managed bean. Constraints can be built in or user defined. User-defined constraints are called custom constraints.
In this way, we can create different custom annotations for validation purposes. You can find the full source code here. It is easy to create and use custom annotations in Java. Java developers will be relieved of redundant code by using custom annotations.
A fully qualified name of your validator can be added to META-INF/services/javax.validation.ConstraintValidator
file. This would allow Hibernate Validator to pick up your validator and it will be used for your custom types.
See more details if needed in this post (section "Use standard constraints for non standard classes")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With