如何在Grails脚本中访问服务? [英] How can Services be be accessed within Grails scripts?
问题描述
关于create-script / run-script的文档很少,所以我想知道是否可以在grails脚本中注入/使用域类。
在一个普通的grails类中,我可以注入一个服务: 'm不知道Grails脚本的内容是哪里
当使用Grails 2.4.3时,这里是我的完整解决方案:
首先,正如错误加载插件管理器:TomcatGrailsPlugin在Grails 2.3数据库迁移中,更改buildConfig.groovy中的tomcat构建类型来编译,而不是像这样构建:
compile':tomcat:7.0.42'
这样可以避免Error loading plugin manager: TomcatGrailsPlugin错误,否则每次运行脚本时都会发生此错误。
接下来,创建脚本/ DoSomething.groovy$ b pre>
includeTargets<< grailsScript(_ GrailsInit)
includeTargets<< grailsScript(_ GrailsBootstrap)
includeTargets<< grailsScript(_ GrailsClasspath)
target(main:调用服务的示例脚本){
取决于(引导程序)
def someService = appCtx。 getBean(someService)//查找服务
someService.runReportOrSomething()//在服务
上调用一个方法
$ b $ setDefaultTarget(main)
上面的代码会导致整个Grails堆栈初始化,所以您的所有服务,域类等都将被设置
最后,运行它:
grails prod do-something --stacktrace -echoOut
您可能会尝试执行grails run-脚本脚本/ DoSomething.groovy,但无论出于何种原因似乎都无效。
The documentation on create-script/run-script is minimal so I'm wondering if it's possible to to inject/use domain classes in grails scripts. In a normal grails class I could inject a service like:
def myService
but I'm not sure where is would go inside of a grails script
When using Grails 2.4.3, here is my complete solution:
First, as is mentioned in "Error loading plugin manager: TomcatGrailsPlugin" on Grails 2.3 Database Migration by Tai, change the tomcat build type in buildConfig.groovy to compile instead of build like so:
compile ':tomcat:7.0.42'
This avoids the "Error loading plugin manager: TomcatGrailsPlugin" error which would otherwise occur every time you run your script.
Next, create scripts/DoSomething.groovy
includeTargets << grailsScript("_GrailsInit")
includeTargets << grailsScript("_GrailsBootstrap")
includeTargets << grailsScript("_GrailsClasspath")
target(main: "An example script that calls a service") {
depends(bootstrap)
def someService = appCtx.getBean("someService") // look up the service
someService.runReportOrSomething() // invoke a method on the service
}
setDefaultTarget(main)
The above code causes the entire Grails stack to initialize, so all your services, domain classes, etc. will be set up for you.
Finally, to run it, do this:
grails prod do-something --stacktrace -echoOut
You might be tempted to do "grails run-script scripts/DoSomething.groovy but for whatever reason that doesn't seem to work.
这篇关于如何在Grails脚本中访问服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!