Mubashir Koul
Mubashir Koul

Reputation: 171

How to use Grails services in a helper class

I have a service created in Grails 2.4 services section. In controller, it is using dependency injection and it is automatically initialized. I want to use the same service say ClassifiedService from a custom helper class which is defined in src/groovy folder.

Question 1: Should I directly call the service as below:

ClassifiedService classifiedService = new ClassifiedService()

If I try to use the dependency injection of Grails, like below, the object is always null.

def classifiedService

Question 2: It is recommended to create an interface for the Service method and use it and initialize it with the actual class?

Upvotes: 0

Views: 805

Answers (1)

micha
micha

Reputation: 49552

You can add you helper class to conf/spring/resources.groovy:

import foo.bar.MyHelperClass

beans = {
   myHelperClass(MyHelperClass)
}

This creates a bean named myHelperClass with class MyHelperClass. All fields inside this bean are autowired (dependency injection happens automatically).

After this you can add the service dependency to myHelperClass using

def classifiedService

You can also inject the helper class into controllers and services. If you need access to the helper class outside controllers/services you can get the instance using

def helper = grailsApplication.mainContext.getBean('myHelperClass')

See the spring section in the Grails documentation for more details

Upvotes: 2

Related Questions