Converting Java -> Grails ... How do I load these properties?
I'm converting a Java web app to Grails (1.2.1). In my Java app, I have a singleton that loads properties from a ".properties" file. I've seen I can put that loading into the "Config.groovy" conf file. If my properties are loaded in Config.groovy, how do I load them in my Java file? Here is how I'm doing it when the Config was loaded in java ...
Long interval = ConfigSingleton.getInstance().getGlob开发者_开发技巧alCacheRefreshInterval();
Thanks, - Dave
Adapted from the Grails User Guide:
You can add your own configuration in grails-app/conf/Config.groovy
, for example:
globalCacheRefreshInterval = 120
Then later in your application you can access these settings in one of two ways. The most common is via the GrailsApplication
object, which is available as a variable in controllers and tag libraries:
Long interval = grailsApplication.config.globalCacheRefreshInterval
The other way involves getting a reference to the ConfigurationHolder
class that holds a reference to the configuration object:
def config = org.codehaus.groovy.grails.commons.ConfigurationHolder.config
Long interval = config.globalCacheRefreshInterval
If you want to acess this configuration from a Java class, you can use:
import org.codehaus.groovy.grails.commons.ConfigurationHolder;
...
Map config = ConfigurationHolder.getFlatConfig();
Long interval = (Long) config.get("globalCacheRefreshInterval");
Attention for the correct type in your Config.groovy
. In the case above, your configuration property must be defined as a Long:
globalCacheRefreshInterval = 120L
You should also checkout the ConfigSlurper class (this is what grails uses to load its config file).
Dave if what you need is to load the properties file as it is without having to move them to the Config.groovy manually, you can the following inside the Config.groovy file:
grails.config.locations = [
"file:" + "/pathWhereFileLives/fileName.properties"
]
This will load all the properties you have in the file in the Grails configuration class. Something to be aware of is that if you have a property in the Config.groovy and the properties file with the same name, the one from the properties file will override the value of the one from Config.groovy
You can find more information about the Grails external configurations here.
精彩评论