JSR 303 Bean Validation – Why on getter and not setter?

Annotating getters doesn’t mean that validation is performed when a getter is invoked. It is just used to identify the property to which a constraint shall apply.

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.

Leave a Comment