JSR 303 Bean验证-为什么使用getter而不使用setter? [英] JSR 303 Bean Validation - Why on getter and not setter?

查看:84
本文介绍了JSR 303 Bean验证-为什么使用getter而不使用setter?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么JSR 303(bean验证)是用于getter方法而不是setter的?将其置于setter方法下是否更合乎逻辑,因为这是字段的入口点,因此应在此之前检查有效性?

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?

推荐答案

注释getter并不意味着在调用getter时执行验证.它仅用于标识约束所适用的属性.

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.

在(通常是公共)getter上放置约束,而不是在(通常是私有)字段上放置约束的最大好处是,约束以这种方式成为类型的公共API的一部分.它们甚至将被添加到生成的JavaDoc中.一种类型的用户无需了解其内部实现即可知道哪种约束适用于它.

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.

注释getter的另一个优点是可以将约束放在基类或接口上的方法上,也可以应用于任何子类型/实现.

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.

这篇关于JSR 303 Bean验证-为什么使用getter而不使用setter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆