Using a Grails service inside a script
Asked Answered
H

1

0

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?

Hosfmann answered 10/4, 2014 at 1:48 Comment(0)
T
2

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)
Tarsal answered 10/4, 2014 at 2:59 Comment(1)
What I don't understand about this answer, is how the script is being invoked. If you are running the script from the grails> prompt (i.e. grails> loadGames) I would expect that you would have to include GrailsInit, and GrailsBootstrap (as you do in the example). It will balk when it hits the appCtx reference. However, if you use the run-script command to do this, it balks when it hits the target statement. I can get simple scripts to work, but anything that involves calls to domain objects and services will fail. This doesn't seem to work in 2.4.2.Deandeana

© 2022 - 2024 — McMap. All rights reserved.