When using JSR-303 annotations to perform bean validation, what is the difference between annotating the field versus the getter?
Is one approach recommended over the other?
Annotation on field
public class Person {
@NotBlank
private String firstName;
public String getFirstName() {
return firstName;
}
public String setFirstName(String firstName) {
this.firstName = firstName;
}
}
Annotation on getter
public class Person {
private String firstName;
@NotBlank
public String getFirstName() {
return firstName;
}
public String setFirstName(String firstName) {
this.firstName = firstName;
}
}
The objective of the JSR-303 standard is to use annotations directly in a Java bean class. JSR 303 specification allows the validation rules to be specified directly into the fields inside any Java class which they are intended to validate, instead of creating validation rules in separate classes.
Spring Framework became JSR303 compliant from version 3 onward I think. Spring Framework 4.0 supports Bean Validation 1.0 (JSR-303) and Bean Validation 1.1 (JSR-349) in terms of setup support, also adapting it to Spring's Validator interface.
A custom validation annotation can also be defined at the class level to validate more than one attribute of the class. A common use case for this scenario is verifying if two fields of a class have matching values.
Very basically, Bean Validation works by defining constraints to the fields of a class by annotating them with certain annotations.
Constraint declarations are placed on classes or interfaces primarily through annotations. A constraint annotation (see Section 2.1, “Constraint annotation”), can be applied to a type, on any of the type's fields or on any of the JavaBeans-compliant properties.
When a constraint is defined on a class, the class instance being validated is passed to the ConstraintValidator. When a constraint is defined on a field, the value of the field is passed to the ConstraintValidator. When a constraint is defined on a getter, the result of the getter invocation is passed to the ConstraintValidator.
The big advantage of putting constraints on (usually public) getters instead on (typically private) fields is that the constraints are part of the type's public API that way. They will even be added to the generated JavaDoc. A user of a type knows that way which constraints apply to it without looking into its internal implementation.
Another advantage of annotating getters is that constraints can be put at methods on base classes or interfaces and also apply for any sub-types/implementations.
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