Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Register new constraint validator for standard bean validation annotation

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;
like image 957
Vadzim Kulinski Avatar asked Dec 05 '17 17:12

Vadzim Kulinski


People also ask

What does @NotNull annotation mean in bean property?

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.

What is Bean Validation constraints?

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.

Can we create custom annotation for validation?

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.


1 Answers

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")

like image 58
mark_o Avatar answered Nov 14 '22 23:11

mark_o