Reputation: 151
Grails 3 allows authors to use startup hooks similar to the ones provided to Grails 2 plugins. I'm looking at defining beans in the doWithSpring
closure, and I'd like to pass values into a new bean based on some configuration values. I can't figure out, however, how to get the grailsApplication instance or the application configuration. How do you do this with Grails 3?
Upvotes: 5
Views: 2143
Reputation: 8587
Under Grails 3, I took Jeff Scott Brown's advice and used GrailsApplicationAware instead:
This is how you go about setting up a configuration bean:
So in your new plugin descriptor you need to change grails 2 style def doWithSpring to a ClosureDoWithSpring as below:
Notice in Grails 2 we injected grailsApplication, in grails 3 all we do is declare the bean:
/*
def doWithSpring = {
sshConfig(SshConfig) {
grailsApplication = ref('grailsApplication')
}
}
*/
Closure doWithSpring() { {->
sshConfig(SshConfig)
}
}
Now to get your plugin configuration:
src/main/groovy/grails/plugin/remotessh/SshConfigSshConfig.groovy
package grails.plugin.remotessh
import grails.core.GrailsApplication
import grails.core.support.GrailsApplicationAware
class SshConfig implements GrailsApplicationAware {
GrailsApplication grailsApplication
public ConfigObject getConfig() {
return grailsApplication.config.remotessh ?: ''
}
}
grails.plugin.remotessh.RemoteSsh.groovy:
String Result(SshConfig ac) throws InterruptedException {
Object sshuser = ac.config.USER ?: ''
Object sshpass = ac.config.PASS ?: ''
...
This is now your configuration object being passed into your src groovy classes. The end user application would pass in the sshConfig bean like this:
class TestController {
def sshConfig
def index() {
RemoteSSH rsh = new RemoteSSH()
....
def g = rsh.Result(sshConfig)
}
Edited to add, just found this :) which is relevant or duplicate question:
Upvotes: 1
Reputation: 27220
Your plugin should extend grails.plugins.Plugin
which defines the getConfig()
method. See https://github.com/grails/grails-core/blob/9f78cdf17e140de37cfb5de6671131df3606f2fe/grails-core/src/main/groovy/grails/plugins/Plugin.groovy#L65.
You should be able to just refer to the config
property.
Likewise you can refer to the inherited grailsApplication
property which is defined at https://github.com/grails/grails-core/blob/9f78cdf17e140de37cfb5de6671131df3606f2fe/grails-core/src/main/groovy/grails/plugins/Plugin.groovy#L47.
I hope that helps.
Upvotes: 2