Looking at language changes in Java 8, the newly allowed locations for annotations (type annotations) prove themselves a very useful feature for Bean Validation.
By putting constraints to type arguments of parameterized types, it finally gets possible to apply constraints to the elements of collections in a concise and intuitive way (BVAL-508):
List<@NotNull @Email String> emails;
Putting the constraints to the
String type argument makes it apparent that they should not be applied to the list object itself, but rather to each contained element.
Similarly, it’s possible to apply constraints to the elements of an array:
String @NotNull @Email emails;
Also cascaded validation gets more flexible with that.
It’s now possible to mandate that the keys and values of maps should be validated
(so far, only values were validated) by using
@Valid like this:
Map<@Valid Customer, @Valid Address> primaryAddressByCustomer;
But it doesn’t end there.
The spec also defines support for
Optional<@Past LocalDate> getRegistrationDate();
As well as for the hierarchy of property types in JavaFX:
Property<@Min(1) Integer> revenue;
Acknowledging that JavaFX provides dedicated non-generic sub-types of
Property for specific data types (e.g.
it is also supported to put constraints on the element itself in this case:
This becomes possible by defining means of "automatic value unwrapping" for specific types such as the JavaFX ones.
Check out the latest spec draft to learn more about how this is handled.
While the spec mandates support for type argument constraints on types such as
Optional and some more,
this can be easily extended via the
This interface is used when the Bean Validation engine needs to obtain the elements of a constrained container.
Custom extractor implementations can be plugged in when bootstrapping a validator,
allowing to use type argument constraints with custom collection types such as the ones defined by Google’s Guava library (e.g.
ListMultimap<@Valid Customer, @Email String> emailsByCustomer;
We are considering to detect custom extractors using the service loader mechanism,
allowing providers of container types to bundle corresponding extractors with their library and making them automatically available to you.
Validation of container elements is by far the most complex feature and we’d like to gather some more feedback on it before committing to it.
Hence its current proposal is added as an appendix to the spec draft.
We are eager to learn about your thoughts and feedback in general, but it’s especially important for this issue due to its complexity.
We’ve compiled a list of open questions around this proposal.
If you have thoughts on any of those, please make sure to let us know, e.g. by commenting below.
The snapshot builds of the reference implementation (Maven GAV
org.hibernate:hibernate-validator:6.0.0-SNAPSHOT) already implement the current proposal, so you can get it from the JBoss Maven repo in order to play with that feature.