使用 Java 类作为 Grails 命令
我有一堆 Java 类,我想将它们用作 Grails 控制器中的命令类。一个典型的例子是:
class Person {
String name
Integer age
public String getName() {return name;}
public String getAge() {return age;}
public void setName(String name) {this.name = name;}
public void setAge(Integer age) {this.age = age;}
}
我希望能够为此类指定约束,以便我可以对其调用 validate()
,并且任何验证错误都将存储在 errors
中> 财产。换句话说,它的行为就像常规的 Grails 命令类一样。
显然我不能直接在.java源文件中声明约束闭包,因为Java不支持闭包。有什么方法可以修改这些类(在运行时),以添加 Grails 命令行为?
I have a bunch of Java classes that I would like to use as command classes in my Grails contollers. A typical example is:
class Person {
String name
Integer age
public String getName() {return name;}
public String getAge() {return age;}
public void setName(String name) {this.name = name;}
public void setAge(Integer age) {this.age = age;}
}
I would like to able to specify constraints for this class such that I can call validate()
on it, and any validation errors will be stored in theerrors
property. In other words, it will behave just like a regular Grails command class.
Obviously I can't declare the constraints closure directly in the .java source file, because Java doesn't support closures. Is there some way I can modify these classes (at runtime), to add Grails command behaviour?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我还没有尝试过,但您可以使用 Groovy 的元编程功能来实现这一点。在
Bootstrap.groovy
中,您可以将静态contraints
闭包添加到您想要验证的所有 Java 类中。还可以使用@Validateable
注释您的类。下面是一个示例:然后将这些类视为 命令类验证它们。
I haven't tried this but you could use Groovy's meta-programming capabilities to achieve this. In your
Bootstrap.groovy
you could add the staticcontraints
closure to all the Java classes that you want to validate. Also annotate your classes with@Validateable
. Here's an example:Afterwards treat these classes like Command classes to validate them.
事实上,Groovy 支持将约束“附加”到 Java 域类,如 Peter Ledbrook (SpringSource) 所描述:
http://blog.springsource.com/2010/08/26/reuse-your-hibernatejpa-domain-model-with-grails/
如上所述在博客文章中,显然不能在 Java 类中定义约束闭包。但是您可以通过遵循以下命名约定创建 Groovy 类来附加约束元数据:
并将其放置在 src/java 文件夹中。
看一下上面提到的博客文章,它对这个主题有很好的介绍。
In fact Groovy supports "attaching" constraints to Java domain classes, as described by Peter Ledbrook (SpringSource):
http://blog.springsource.com/2010/08/26/reuse-your-hibernatejpa-domain-model-with-grails/
As described in the blog post, you obviously can't define a constraints closure in the Java class. But you can attach constraint meta-data by creating a Groovy class following this naming convention:
and place this in the src/java folder.
Take a look at the blog post mentioned above, it's a very good introduction to this topic.