Reputation: 1990
I need a custom command-line task in my grails app, so I have created a script using grails create-script my-script
.
From that script, I would like to access some of the application's config properties. Normally you can do this via grailsApplication.config
. However, it seems grailsApplication
is not available from within the context of a command-line script. The following script....
includeTargets << grailsScript("Init")
target(main: "The description of the script goes here!") {
println grailsApplication.config.mysetting
}
setDefaultTarget(main)
...yields (when run as grails my-script
):
groovy.lang.MissingPropertyException: No such property:
grailsApplication for class: MyScript
I also tried ConfigurationHolder.config
, which just returns null.
So how can I access application config from a script launched from the command-line?
Upvotes: 1
Views: 1894
Reputation: 116
I can't yet write a comment, so I'm posting an answer.
I think the solution using the _GrailsPackage script suggested by snowindy is to be preferred. The reason is that using bootstrap actually boots the application, which means connecting to the database, executing the BootStrap.groovy, etc. Just using _GrailsPackacke with the compile and createConfig dependencies just requires a compilation run.
Dependending on what your script does this is probably what you want to have. In my case I generated some SQL scripts that can be customized via settings in the Config.groovy, so booting the app was just slowing things down.
Cheers, Ben
Upvotes: 1
Reputation: 3251
1) Refer to _GrailsPackage at the top of your script:
includeTargets << grailsScript('_GrailsPackage')
2) Depend on compile and createConfig targets described in _GrailsPackage
target(main: "Your main") {
depends(compile,createConfig)
println "My value: ${config.my.config.value}"
}
Upvotes: 2
Reputation: 1990
The trick is to pull in the boostrap targets and depend on them, as shown below. Note that the application context object is called grailsApp
, and not grailsApplication
at this stage.
includeTargets << grailsScript('_GrailsBootstrap')
target(main: "The description of the script goes here!") {
depends checkVersion, configureProxy, bootstrap
println grailsApp.config.mysetting
}
setDefaultTarget(main)
You might also be able to use the run-script command. This didn't work for me, because it tries to initialise a Hibernate session. My app uses mongodb as a primary datastore, which requires that you uninstall the Hibernate plugin - so run-script fails.
Upvotes: 3