In a project I was asked to maintain the user login history. I wrote all my business logic in a service say “UtilityService” and captured the login event successfully then I required to call this service. For that I used the following code to call the service:
import org.codehaus.groovy.grails.web.context.ServletContextHolder as SCH import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes
String appAttribute = GrailsApplicationAttributes.APPLICATION_CONTEXT Object appContext = SCH.servletContext.getAttribute(appAttribute) def utilityService = appContext.utilityService utilityService.saveLoginHistory()
Here I am fetching application context using ServletContextHolder class and GrailsApplicationAttributes interface then injecting the UtilityService bean. Now I can call any method of the service using bean.