1

I just wanted to know that is it possible to set the value of a variable in Grails controller from the configuration file like config.groovy or some other configuration file?

For instance , my controller is as follows:

class WebsiteController {
    def show(){
        String user_name = "value to be fetched from configuration file"
    }
}

Here, I want to set the value of user_name from the configuration file. I have no idea how to do this. I have been given this requirement by my senior. I searched online but couldn't find anything relevant. If it is possible, please tell me the approach. Thanks

clever_bassi
  • 2,392
  • 2
  • 24
  • 43
  • 1
    Have a look at [Externalized Configuration](http://grails.org/doc/latest/guide/conf.html#configExternalized). – dmahapatro Jul 23 '14 at 18:50

3 Answers3

4

Here is an example of properties added to the Config.groovy:

environments {
  development {
    tipline.email.address="joe@foo.us"
    grails.logging.jul.usebridge = true
  }
  staging {
    tipline.email.address="mailinglist@foo.us"
    grails.logging.jul.usebridge = true
  }
  production {
    tipline.email.address="mailinglist@foo.us"
    grails.logging.jul.usebridge = false
    // TODO: grails.serverURL = "http://www.changeme.com"
  }
}

To access them in your code:

    println("Email :"+grailsApplication.config.tipline.email.address)
Joe
  • 1,219
  • 8
  • 13
1

Properties are properties =)

Properties properties = new Properties()
File propertiesFile = new File('test.properties')
propertiesFile.withInputStream {
    properties.load(it)
}

def runtimeString = 'a'
assert properties."$runtimeString" == '1'
assert properties.b == '2'

Taken from Get values from properties file using Groovy

Community
  • 1
  • 1
Dakota Brown
  • 730
  • 7
  • 20
1

Another possibility is to inject parameters into the controller by using a property override configuration:

// Config.groovy:

website.user = "me"

beans {
    '<replace by package>.WebsiteController' {
            userName = website.user
    }
}


// Controller:

class WebsiteController {
    String userName

    def show(){
        //.. use userName ..
    }
}

In this case you don't need grailsApplication and you don't hard code the configuration path in the Controller. Less dependencies make testing easier. :)

Martin Hauner
  • 1,593
  • 1
  • 9
  • 15