JSR-303 Annotating Field vs Getter
Asked Answered
B

1

8

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;
  }
}
Burg answered 10/1, 2018 at 4:13 Comment(0)
E
14

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.

Epididymis answered 10/1, 2018 at 4:32 Comment(2)
Your link to a question is brokenLiddle
@GabrielOshiro, thank you! I The important contents of the link was added to the answer to make sure the solution available, now I have removed the link.Epididymis

© 2022 - 2024 — McMap. All rights reserved.