在域类中使用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?
示例代码:
Sample code:
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屋!