在war文件中创建WEB-INF外部的配置属性文件

时间:2016-07-19 07:36:36

标签: java spring grails groovy

我已经创建了小grails应用程序现在我需要处理配置文件中的动态参数,我已经为数据源做了,我在最后放在datasource.groovy文件中的代码下面

grails.config.locations = ["classpath:config.properties"] 

并在grails-app / config中创建了一个config.properties文件,其工作正常,但问题是我生成war文件,属性文件位置在WEB-INF / classes中,但我需要WEB-INF之外的那个文件,eaxmple结构如:

myApp:

  • config.properties
  • WEB-INF
  • assets
  • css
  • JS​​ ...等

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:1)

我最喜欢的选项:在您的应用服务器中指定一个额外的类路径,并将您的属性文件放在此路径中。

E.g。在Tomcat中,它将是位于 $ CATALINA_HOME / conf / catalina.properties (或 $ CATALINA_BASE / conf / catalina.properties ,如果存在)的'common.loader'属性。 (如果你使用像 tomcat7-maven-plugin 这样的< 配置>标签有'< additionalClasspathDirs >'元素你在哪里可以指定其他类路径。)

有关此主题的更多讨论,请参阅this blog

答案 1 :(得分:1)

对于Grails< 3.0 - 在配置文件中,您可以放入或取消注释以下代码。把它放在config.groovy文件的末尾,这样它将覆盖预定义的配置属性:

// keep it at the end of the file - so you can override with external config
grails.config.locations = [ "classpath:${appName}-config.properties",
                            "classpath:${appName}-config.groovy",
                            "file:${userHome}/.grails/${appName}-config.properties",
                            "file:${userHome}/.grails/${appName}-config.groovy"]

if (System.properties["${appName}.config.location"]) {
    grails.config.locations << "file:" + System.properties["${appName}.config.location"]
}

然后创建 myapp-config.properties ,甚至更好, myapp-config.groovy 格式文件home .grails文件夹(&#34; myapp&#34;是你的应用程序名称) 因此,您可以为开发环境中的每个Grails应用程序提供外部配置文件。 对于生产,它需要在Tomcat类路径中 - 所以一个好的地方是将它放在tomcat lib文件夹中。

答案 2 :(得分:0)

假设您的应用程序名为myapp,并将名为myapp-config.groovy的配置文件放在用户主目录下名为myapp的文件夹中:

def loadExternalConfiguration() {
    def contextPath = grailsApplication.mainContext.servletContext.contextPath.substring(1)
    def userHome = System.properties['user.home']
    def userConfigDir = new File("${userHome}/${contextPath}")
    if (userConfigDir.exists()) {
        File configFile = new File("${userConfigDir}/${contextPath}-config.groovy")
        if (configFile.exists() && configFile.isFile()) {
            def configSlurper = new ConfigSlurper()
            def configPart = configSlurper.parse(configFile.toURI().toURL())
            grailsApplication.config.merge(configPart)
        }
    }
}
相关问题