Reputation: 16379
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?
Upvotes: 17
Views: 13539
Reputation: 574
To summarize Burt and Remis' answers:
In the domain custom validator, you have to use obj.testService
rather than use testService
directly. If you wanna use service in the domain custom validator:
static constraints = {
name validator: { value, obj ->
if (obj.testService.someMethod(value)) {
...
}
}
}
But in other methods, including afterInsert
and other private/public methods, use testService
is fine.
def someMethod() {
def user = testService.serviceMethod();
....
}
Upvotes: 1
Reputation: 374
Short answer is. Yes you can use service inside domain class.
Here is an sample code where domain class gets access to the authenticate service from acegi plugin. It works without problems.
class Deal {
def authenticateService
def afterInsert() {
def user = authenticateService.userDomain();
....
}
....
}
Upvotes: 12
Reputation: 75681
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)) {
...
}
}
}
Upvotes: 28