向 Groovy 类(不是 Grails 域类!)的属性添加约束
我们如何向 Groovy 类的属性添加一些常见约束(即 maxLength、可为空)?我知道我们可以在 Grails 域类中做到这一点,但是如果这是一个 Groovy 类(我将它用作我的 Grails 项目的 DTO 类),这可能吗?
太感谢了!
How can we add some common constraints (i.e. maxLength, nullable) to a property of a Groovy class? I know we can do it at Grails domain class, but is it possible if that is a Groovy class (I use it as a DTO class for my Grails project)?
Thank you so much!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以向命令类添加约束。如果命令类与控制器位于同一个 .groovy 文件中(在 Groovy 中,每个 .groovy 文件中可以有多个公共类),则无需为 Grails 执行任何特殊操作即可将其识别为命令类。
但是,如果您的命令类位于其他位置(例如在 src/groovy 下),则需要使用 @Validateable 进行注释,并将包名称添加到 grails.validateable.packages 中> Config.groovy 中的参数。下面是一个与控制器不在同一文件中的命令示例
将以下内容添加到 Config.groovy
命令类具有 Grails 添加的 validate() 方法。调用此方法后,任何错误都将在
errors
属性中显示(根据域类)。You can add constraints to command classes. If a command class is in the same .groovy file as a controller (in Groovy you can have more than one public class in each .groovy file), you don't need to do anything special for Grails to recongise it as a command class.
However, if your command class is somewhere else (e.g. under src/groovy), you need to annotate it with
@Validateable
and add the package name to thegrails.validateable.packages
parameter inConfig.groovy
. Here's an example of a command that's not in the same file as a controllerAdd the following to
Config.groovy
Command classes have a
validate()
method added by Grails. After this method is called, any errors will be available in theerrors
property (as per domain classes).使用 grails 命令对象 可能是你最好的选择。它有约束和验证,但没有数据库支持。它通常是控制器使用的值对象,但您可以在控制器外部实例化一个值对象,不会出现任何问题。
Using a grails Command Object is probably your best bet. It has constraints and validation, but no database backing. It's normally a value object that controllers use, but you could instantiate one outside of a controller without any problems.
不确定这是否与您的使用相关(我对 DTO 不熟悉),但在当前版本(2.3.8)中,您还可以向抽象类添加 Grails 约束,并且它们将由扩展的域继承它。不过您的 IDE 可能不喜欢它;)
Not sure if this is relevant to your use (I am not familiar with DTOs), but in the current version (2.3.8), you can also add Grails constraints to an abstract class, and they will be inherited by the domains that extend it. Your IDE might not like it though ;)