【问题标题】:Grails: Initialize variable using Configuration fileGrails:使用配置文件初始化变量
【发布时间】:2014-09-15 02:20:31
【问题描述】:

我只是想知道是否可以从配置文件(如 config.groovy 或其他配置文件)中设置 Grails 控制器中变量的值?

例如,我的控制器如下:

class WebsiteController {
    def show(){
        String user_name = "value to be fetched from configuration file"
    }
}

在这里,我想从配置文件中设置 user_name 的值。我不知道该怎么做。 我的前辈已经给了我这个要求。我在网上搜索,但找不到任何相关的东西。如果可能,请告诉我方法。 谢谢

【问题讨论】:

标签: grails groovy configuration initialization


【解决方案1】:

属性就是属性 =)

Properties properties = new Properties()
File propertiesFile = new File('test.properties')
propertiesFile.withInputStream {
    properties.load(it)
}

def runtimeString = 'a'
assert properties."$runtimeString" == '1'
assert properties.b == '2'

取自Get values from properties file using Groovy

【讨论】:

    【解决方案2】:

    以下是添加到 Config.groovy 的属性示例:

    environments {
      development {
        tipline.email.address="joe@foo.us"
        grails.logging.jul.usebridge = true
      }
      staging {
        tipline.email.address="mailinglist@foo.us"
        grails.logging.jul.usebridge = true
      }
      production {
        tipline.email.address="mailinglist@foo.us"
        grails.logging.jul.usebridge = false
        // TODO: grails.serverURL = "http://www.changeme.com"
      }
    }
    

    在您的代码中访问它们:

        println("Email :"+grailsApplication.config.tipline.email.address)
    

    【讨论】:

      【解决方案3】:

      另一种可能性是使用property override configuration 将参数注入控制器:

      // Config.groovy:
      
      website.user = "me"
      
      beans {
          '<replace by package>.WebsiteController' {
                  userName = website.user
          }
      }
      
      
      // Controller:
      
      class WebsiteController {
          String userName
      
          def show(){
              //.. use userName ..
          }
      }
      

      在这种情况下,您不需要grailsApplication,也不需要在控制器中硬编码配置路径。更少的依赖使测试更容易。 :)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-26
        • 2012-12-02
        • 2016-11-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多