4

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?

E.g.

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

}

GGizmos
  • 3,443
  • 4
  • 27
  • 72
  • I'm thinking that beforeUpdateProcess itself should be a static method of fooService in which case the solution is simply FooService.beforeUpdateProcess(foo). Is that the right way to handle it? – GGizmos Dec 10 '16 at 20:36
  • 1
    I would suggest not using static methods in general, and especially in domains or services. – Demian Dec 10 '16 at 23:54

1 Answers1

11

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
Anatoly
  • 456
  • 5
  • 13