Thursday, September 5, 2013



Accessing Grails components (Controllers and Services etc) from grails-app in classes /src/groovy

Requirement:
There is a need , sometimes, for groovy classses in /src/groovy/pkg1/ to access/work with Grails components (ex. services).  The service/controller/domain/views components are in /grails-app directory and can see/access each other. The classes (.groovy or .java) in /src/groovy or /src/java cannot see them.

Solution:

//Import the required classes
import org.codehaus.groovy.grails.web.context.ServletContextHolder as SCH
import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes as GA
class GetServicesHelper {
   def getMyService(){
        //Get ServletContext 
        def servletContext = SCH.servletContext
        //Get GrailsApplicationContext from GrailsApplicationAttributes saved in ServletContext
        def grailsApplicationContext = servletContext.getAttribute(GA.APPLICATION_CONTEXT)
        //Get the service that is injected into Grails Application Context
        def myService = grailsApplicationContext.myService
        return myService
    }
}

No comments:

Post a Comment