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

前端 未结 4 1670
广开言路
广开言路 2020-12-29 20:25

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 poin

4条回答
  •  长情又很酷
    2020-12-29 21:11

    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.

提交回复
热议问题