grails - Grails 中如何覆盖外部配置文件中的配置变量,以便依赖于该变量的变量也被更新?

标签 grails groovy config lazy-evaluation

我的 grails 应用程序中有一个外部和内部配置:

Config.groovy

root = "/home/baseConf"

test {
    dir =  root + "/testDir"
}

外部.groovy

root = "/home/externalConf"

我有内部 Controller :

println "${grailsApplication.config.root}"
println "${grailsApplication.config.test.dir}"

打印内容:

/home/externalConf
/home/baseConf/testDir

我想要打印的内容:

/home/externalConf
/home/externalConf/testDir

我应该如何通过在外部配置文件中交换这个基本变量来更改在 Config.groovy 中使用一个基本变量的许多变量(如上例所示)?这样的事情可能吗?

最佳答案

您需要更改您的 dir 变量(在测试内)。检查下面的代码。

test {
    dir =  "${-> root}/testDir"
}

此更改是必要的,因为您希望在调用 dir 时对其进行评估,而不是在加载 Config 时进行评估。这称为后期绑定(bind)(惰性求值)(请参阅此处 Ian Roberts 的回答: Reusing Grails variables inside Config.groovy )。

需要注意的是,它与 Groovy 语言(而不是 Grails)有关。

热切评估策略如下所示:

def x = 1
def s = "The value of x is: ${x}"
println s //The value of x is: 1

x = 2
println s //The value of x is: 1

对于另一方,惰性求值策略将按需求值表达式(按需调用):

def x = 1
def s = "The value of x is: ${-> x}"
println s //The value of x is: 1

x = 2
println s //The value of x is: 2    

关于grails - Grails 中如何覆盖外部配置文件中的配置变量,以便依赖于该变量的变量也被更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28811019/

相关文章:

grails - 为什么在第一次访问hasMany关系时grails抛出空指针异常?

Grails 2.0 和 servletContext

deployment - 如何避免 glassfish 部署所有以前的项目?

tomcat - "<Parameter>"与 Tomcat 上下文中的 "<Environment>"条目

maven - Sonatype Nexus的Grails Release插件maven-deploy命令失败401错误

groovy - 更改嵌套在另一个映射中的映射的值

grails - "Overloading"标准 GORM CRUD 方法

grails - Grails应用程序中Groovy代码的编译

configuration - 如何使用命令行 dpkg 选项解压 conf 并跳过 postinst 脚本

Grails:有没有办法让 findAll() 没有查询但有分页和排序?