6

I want to use the contents of a config file in several ways, including in integration tests and in my BootStrap. If my config file is under src/groovy and is called "com.corp.MyConfig.groovy", what should I pass to the ConfigSlurper parse method?

Jim Norman
  • 751
  • 8
  • 28
  • config = new ConfigSlurper().parse(new File(configFile).toURI().toURL()) works if "configFile" is "src/groovy/com/corp/MyConfig.groovy", but I'm hoping for something more elegant -- an expression that doesn't contain "src/groovy", especially. – Jim Norman May 25 '11 at 15:38

3 Answers3

3

I guess what happens is that your Groovy file gets compiled and ends up being a class in your binary directory (classpath). Instead of trying to load it via the URL try to load the script class.

Class scriptClass = getClass().classLoader.loadClass('com.corp.MyConfig')
ConfigObject config = new ConfigSlurper().parse(scriptClass)
Benjamin Muschko
  • 32,442
  • 9
  • 61
  • 82
2

If your config file is available on the classpath, I would suggest using ClassLoader.getResource() to get it:

URL url = MyClass.class.getClassLoader().getResource("com/corp/MyConfig.groovy");
config = new ConfigSlurper().parse(url);
dogbane
  • 266,786
  • 75
  • 396
  • 414
  • This should work in a unit test environment, right? I am using the unit test class name as "MyClass"; 'url' is null. – Jim Norman May 25 '11 at 16:16
  • Hmm, that means that it can't find your config on the classpath. Try changing the resource name to to `groovy/com/corp/MyConfig.groovy`. – dogbane May 25 '11 at 16:31
  • No luck with adding "groovy" to the path. – Jim Norman May 25 '11 at 16:59
  • @jim-norman do you have src on the classpath? Maybe you have another directory called classes or bin on the classpath instead. You need to make sure that your config.groovy is present in a directory which is on the classpath. – dogbane May 26 '11 at 06:58
0

From a POGO you can also use:

import grails.util.Holders

class Foo {
    def bar() {
        println(Holders.config.grails.serverURL)
    }
}

From: How do I get at the goodies in my Grails Config.groovy at runtime?

Community
  • 1
  • 1
Cookalino
  • 1,559
  • 14
  • 19