在域类中使用 grails 服务 [英] Using grails service in domain class
问题描述
我想在我的 Grails 应用程序中使用一个服务.但是,它始终为空.我正在使用 Grails 1.1 版.我该如何解决这个问题?
I want to use a service in my Grails application. However, it is always null. I am using Grails version 1.1. How can I solve this problem?
示例代码:
class A{
String name;
def testService;
static transients=['testService']
}
我可以在域类中使用服务吗?
Can I use a service inside a domain class?
推荐答案
那应该可行.请注意,由于您使用的是def",因此无需将其添加到瞬态列表中.您是否尝试从静态方法访问它?它是一个实例字段,因此您只能从实例中访问它.
That should work. Note that since you're using 'def' you don't need to add it to the transients list. Are you trying to access it from a static method? It's an instance field, so you can only access it from instances.
将服务注入域类的典型用例是用于验证.自定义验证器通过正在验证的域类实例,因此您可以从中访问服务:
The typical use case for injecting a service into a domain class is for validation. A custom validator gets passed the domain class instance being validated, so you can access the service from that:
static constraints = {
name validator: { value, obj ->
if (obj.testService.someMethod(value)) {
...
}
}
}
这篇关于在域类中使用 grails 服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!