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

yapkm01 picture yapkm01 · Jun 8, 2011 · Viewed 9.4k times · Source

I don't understand why JSR 303 (bean validation) is for the getter methods and not setter? Isn't it more logical to put it under setter method since that is the entry point into a field and validation should be checked prior to that?

Answer

Gunnar picture Gunnar · Jun 8, 2011

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.