问题
I'm trying to use a Grails service inside the following Grails script
includeTargets << grailsScript("_GrailsInit")
target(loadGames: "The description of the script goes here!") {
def listFile = new File('list.txt')
listFile.eachLine {
def result = ctx.getBean("bggService").search(it)
println it + " " + result.length()
}
}
setDefaultTarget(loadGames)
I've seen about a dozen different webpages each offering a different combination of ctx
appCtx
, and applicationContext
(as well as many others) as suggestions, however none of them work. Typically they complain that the context variable that I am trying to use does not exist.
Why can't Grails just use services inside a script in exactly the same way that they get used in controllers?
What is the right way to use a Grails service inside a Grails script?
回答1:
Getting hold of ApplicationContext
and grailsApplication
is possible though bootstrap command. Include _GrailsBootstrap
script, then call configureApp ()
or depend on it in order to make ApplicationContext
available in script:
includeTargets << grailsScript("_GrailsInit")
includeTargets << grailsScript("_GrailsBootstrap")
target(loadGames: "The description of the script goes here!") {
depends(configureApp)
def listFile = new File('list.txt')
listFile.eachLine {
//Once configureApp() called ApplicationContext can be accessed as appCtx
def result = appCtx.getBean("bggService").search(it)
println it + " " + result.length()
}
}
setDefaultTarget(loadGames)
来源:https://stackoverflow.com/questions/22977227/using-a-grails-service-inside-a-script