如何从grails中的属性文件中获取值?

时间:2016-05-19 09:16:19

标签: grails

如何从属性文件中获取值?我应该把文件放在哪里?
谢谢

编辑:我使用grails 3.1.5而且我试图从工作类(石英)中获取属性

2 个答案:

答案 0 :(得分:5)

将您的媒体资源直接保存在 Config.groovy 文件中。

或者您可以创建 .properties 文件以保留属性并将此文件添加到 Config.groovy

  

grails.config.locations = [“classpath:grails-app-config.properties”]

并使用

在应用程序的任何位置访问它
  

grailsApplication.config。 “PROPERTYNAME”

答案 1 :(得分:0)

我们有这样一个特点:

/**
 * Load config from config locations given by property grails.config.locations.
 * Based on http://grails.1312388.n4.nabble.com/Grails-3-External-config-td4658823.html
 */
trait ExternalConfigurationLoader implements EnvironmentAware {

    @Override
    void setEnvironment(Environment environment) {
        loadExternalConfigLocations(environment)
    }

    void loadExternalConfigLocations(Environment environment) {
        if (environment) {
            def configLocations = findConfigLocationsFromApplicationGroovy()
            DefaultResourceLocator resourceLocator = new DefaultResourceLocator()
            for (String configLocation in configLocations) {
                loadConfigLocation(configLocation, grails.util.Environment.current.name, environment, resourceLocator)
            }
        }
    }

    List<String> findConfigLocationsFromApplicationGroovy() {
        def applicationGroovy = this.getClass().classLoader.getResource('application.groovy')
        if (applicationGroovy) {
            def applicationConfiguration = new ConfigSlurper(grails.util.Environment.current.name).parse(applicationGroovy)
            return applicationConfiguration.grails.config.locations
        }
        []
    }

    void loadConfigLocation(String configLocation, String currentEnvironmentName, Environment environment, ResourceLocator resourceLocator) {
        def configurationResource = resourceLocator.findResourceForURI(configLocation)
        if (configurationResource) {
            log.debug "External config '$configLocation' found. Loading."
            def configSlurper = new ConfigSlurper(currentEnvironmentName)
            def config = configSlurper.parse(configurationResource.getURL())
            environment.propertySources.addFirst(new MapPropertySource(configLocation, config))
        } else {
            log.debug "External config '$configLocation' not found."
        }
    }

}

然后我们可以将此特征添加到Application.groovy

class Application extends GrailsAutoConfiguration implements ExternalConfigurationLoader {

并在application.groovy中配置外部配置文件:

grails.config.locations = ["classpath:myapp-config.groovy", "file:dev-config.groovy"]

如果使用Tomcat,则可以将myapp-config.groovy放入Tomcats lib文件夹中。

注意:此变体仅支持.groovy类型的外部配置文件,但如果您愿意,可以将其扩展为支持.yml.properties。另请注意,此示例在application.yml中覆盖环境块的值时存在一些问题,因此如果您计划覆盖dataSource,则需要从dataSource移动application.yml的默认配置首先到application.groovy

还有一个插件正在为grails.config.locations添加类似的支持。见https://github.com/sbglasius/external-config