Reputation: 797
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
Upvotes: 2
Views: 658
Reputation: 111
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.
Upvotes: 1
Reputation: 8587
To use domainClasses in scripts:
includeTargets << grailsScript("_GrailsBootstrap")
at the top
Then within function requiring access to add:
depends(bootstrap)
def myDomainClass = grailsApp.classLoader.loadClass("myapp.MyDomainClass")
def myDomainClassList = myDomainClass.list()
There is lots of information on all of this in The Definitive Guide to Grails 2
Upvotes: 1