简体   繁体   中英

Using grails service in domain class

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?

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)) {
         ...
      }
   }
}

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();
        ....
    }
....
}

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();
    ....
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM