tags:

views:

163

answers:

2

In my grails application I want use service.However it is always coming as null.I am using grails 1.1 version.How to solve this problem.

Sample code:

 class A{

 String name;
 def testService;

 static transients=['testService']

 }

Can we use service inside domain class?

+1  A: 

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)) {
         ...
      }
   }
}
Burt Beckwith
Hi I am trying to access it from def onLoad ={} closure.
BlackPanther
Looks like the dependency injection happens after the onLoad event, so you'll need to pull it from the application context instead. Add this import: "import org.codehaus.groovy.grails.commons.ApplicationHolder as AH" and then in your onLoad you can reference the service as "def testService = AH.application.mainContext.testService"
Burt Beckwith
+1  A: 

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();
        ....
    }
....
}
Remis B
This is actually the better answer! I had the whole thing backwards. I shouldn't have tried to access the db from the service, I should inject the service into the Domain class and run the code with the grails "triggers" like afterInsert, as you point out.
ראובן