2014-04-10 36 views
0

我嘗試使用下面的Grails腳本中一個Grails服務使用一個Grails服務的腳本

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) 

我見過十幾個不同的網頁每提供的ctxappCtx不同的內線組合,和applicationContext(以及許多其他)作爲建議,但是它們都不起作用。通常他們會抱怨說我嘗試使用的上下文變量不存在。

爲什麼Grails不能在腳本中使用服務,其方式與在控制器中使用的方式完全相同?

在Grails腳本中使用Grails服務的正確方法是什麼?

回答

2

通過bootstrap命令可以獲得ApplicationContextgrailsApplication的可能性。包括_GrailsBootstrap腳本,然後調用configureApp()或爲了使腳本中可用ApplicationContext依賴於它:

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) 
+0

我不明白這個答案是什麼,是腳本是如何被調用。如果您從** grails> **提示符(即** grails> ** loadGames)運行腳本,則希望您必須包含GrailsInit和GrailsBootstrap(如您在示例中所做的那樣)。它會在碰到appCtx參考時出現障礙。但是,如果您使用** run-script **命令來執行此操作,它在達到目標語句時會變得很慢。我可以獲得簡單的腳本,但涉及對域對象和服務的調用的任何操作都將失敗。這在2.4.2中似乎不起作用。 – mfortner

相關問題