Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails 2.x service injection in Groovy/src

I'd like to inject my service in Groovy/src class. The normaln dependency injection doesn't work:

...
def myService
...

I'm able to use this (it works):

def appCtx = ApplicationHolder.application.getMainContext()
def myService = appCtx.getBean("myService");

but the ApplicationHolder is deprecated. Is there any better solution?

Thanks for any suggestion

like image 843
kuceram Avatar asked May 17 '12 17:05

kuceram


2 Answers

The replacement of ApplicationHolder can be Holders, you can also use it in static scope:

import grails.util.Holders
...

def myService = Holders.grailsApplication.mainContext.getBean 'myService'
like image 181
César Avatar answered Oct 31 '22 21:10

César


Check following Grails FAQ to get access to the application context from sources in src/groovy - http://grails.org/FAQ#Q: How do I get access to the application context from sources in src/groovy?

There is no ApplicationContextHolder class equivalent to ApplicationHolder. To access to a service class called EmailService from a Groovy class in src/groovy, access the Spring bean using:

import org.codehaus.groovy.grails.web.context.ServletContextHolder as SCH
import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes as GA
def ctx = SCH.servletContext.getAttribute(GA.APPLICATION_CONTEXT)
def emailService = ctx.emailService
like image 13
Ben W Avatar answered Oct 31 '22 20:10

Ben W