Converting Java -> Grails … How do I load these pr

2020-07-25 09:23发布

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().getGlobalCacheRefreshInterval();

Thanks, - Dave

标签: grails
3条回答
爷、活的狠高调
2楼-- · 2020-07-25 09:54

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.

查看更多
手持菜刀,她持情操
3楼-- · 2020-07-25 10:08

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
查看更多
家丑人穷心不美
4楼-- · 2020-07-25 10:11

You should also checkout the ConfigSlurper class (this is what grails uses to load its config file).

查看更多
登录 后发表回答