Adding attributes to your annotation
It's a good idea to create a new
Bean Validation annotation if you reuse the validation several times, usually across several projects. To improve the reusability you may want to parametrize the validation code. For example, for your current project to do the search in
openlibrary.org for ISBN is OK, but in another project, or even in another entity of your current project, you do not want to call this particular URL. The code of the annotation has to be more flexible.
This flexibility can be achieved by attributes. For example, we can add a boolean search attribute to our
ISBN annotation in order to switch on or off the internet search for validation. To implement this functionality, just add the
search attribute to the
ISBN annotation code that you can find in the package in
com.yourcompany.invoicing.annotations folder:
public @interface ISBN {
boolean search() default true; // To (de)activate web search on validate
// ...
}
This new search attribute can be read from the validator class what you can find in the folder
com.yourcompany.invoicing.validators:
public class ISBNValidator implements ConstraintValidator<ISBN, Object> {
// ...
private boolean search; // Stores the search option
public void initialize(ISBN isbn) { // Read the annotation attributes values
this.search = isbn.search();
}
public boolean isValid(Object value, ConstraintValidatorContext context) {
if (Is.empty(value)) return true;
if (!validator.isValid(value.toString())) return false;
return search ? isbnExists(value) : true; // Using 'search'
}
// ...
}
Here you see the use of the
initialize() method: the source annotation can be used to initialize the validator, in this case simply by storing the
isbn.search() value to evaluate it in
isValid().
Now you can choose whether you want to call our REST service or skip the ISBN validation:
public class Product{
//...
@ISBN(search=false) // In this case no internet search is done to validate the ISBN
private String isbn;
//...
}
Now try out your application and you will notice that the validation will not take place.
Summary
Congratulations! You have learned how to add attributes to your annotation. In this last lessons you have learned several ways to do validation in an OpenXava application. Also, you know how to encapsulate the reusable validation logic in annotations with custom Bean Validation.
Validation is an important part of the logic of your application, and we encourage you to put it into the model, i. e. into your entities. We demonstrated several examples for this technique in the past few lessons. Sometimes it is more convenient to put logic outside your model classes. You will learn that in the next lessons.