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

前端 未结 4 1662
广开言路
广开言路 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 20:49

    Its a very good question and something that I have never paid attention to. But I think I know the answer ( and also why I never got this question myself).

    If you are looking at this, from the point of view that, the annotation defines where the validation will happen, then putting it on getter does not make sense. ( why not validate while storing the value itself..). But this is not how it works...

    The programmer needs to tell the validation framework, which properties needs to be validated. So you can put the annotation directly on the attribute (which I prefer) or you can put it on the getter. Both of them signify read operation. The Framework needs to read all the attributes of your class, that will have to be validated. So in this case, putting on setter makes no sense at all.. The key to understand is the perspective...

    I hope it makes sense.

提交回复
热议问题