Using a Grails service inside a script

谁都会走 提交于 2020-01-16 20:34:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!