简体   繁体   中英

Grails How to call service from static method of domain class?

I have a static method on my domain class, and want to get all the business logic out of the domain class definition into the service, but I can't call the service in the domain class static method since the service itself is defined on the instance not the domain class.

What the best solve for this?

Eg

class Foo {
   def fooService
   Integer count =0
   String name

   static void updateFoo(String name) {
      def foo = FindByName(name)
      fooService.beforeUpdateProcess(foo)   //fooService unavailable here  
      foo.count+=1
      foo.save()
   }

}

Since services are beans, you would access them the way you would generically access any bean from the application context. Grails has a Holders helper for this.:

FooService fooService = grails.util.Holders.applicationContext.getBean('fooService') as FooService

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