【问题标题】:Create configuration properties file outside WEB-INF in war file在war文件中在WEB-INF之外创建配置属性文件
【发布时间】:2016-07-19 07:36:36
【问题描述】:

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

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

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

我的应用:

  • config.properties
  • WEB-INF
  • 资产
  • CSS
  • js...等

我该如何解决这个问题?

【问题讨论】:

    标签: java spring grails groovy


    【解决方案1】:

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

    例如在 Tomcat 中,它将是位于 $CATALINA_HOME/conf/catalina.properties 的“common.loader”属性(或 $CATALINA_BASE/conf/catalina.properties,如果存在)。 (如果你使用类似 tomcat7-maven-plugin 的东西,它的 configuration> 标签有 'additionalClasspathDirs>' 元素,你可以在其中指定额外的类路径)。

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

    【讨论】:

    • 不确定这是否适用于 tomcat7。我修改 common.loader 并使用 sudo service tomcat7 restart 重新启动 tomcat 并执行 ps aux | grep tomcat7 并看到 classpath 参数不包含 common.loader 路径
    【解决方案2】:

    对于 Grails

    // 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 文件夹(“myapp”是您的应用程序名称) 因此,您可以为开发环境中的每个 Grails 应用程序提供一个外部配置文件。 对于生产,它需要在 Tomcat 类路径中 - 所以最好将它放在 tomcat lib 文件夹中。

    【讨论】:

      【解决方案3】:

      假设您的应用程序名为 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)
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2018-08-22
        • 2010-11-24
        • 2023-04-11
        • 2015-10-17
        • 1970-01-01
        • 2019-02-12
        • 2011-08-09
        • 2023-03-14
        • 1970-01-01
        相关资源
        最近更新 更多