根据this question,我认为我可以在(例如)resources.groovy
def currentEnv = Environment.current
if (currentEnv == Environment.CUSTOM && currentEnv.name == 'mock') {
println 'Do some stuff for the mock env'
}
if-statement中的代码应该在我运行时执行(例如)grails run-app -Denv=mock
,但事实并非如此,我做错了什么?
答案 0 :(得分:9)
您必须使用方法Environment.executeForCurrentEnvironment()
,如下所示:
import grails.util.Environment
grails.util.Environment.executeForCurrentEnvironment {
development {
println 'Running in DEV mode.'
}
production {
println 'Running in production mode.'
}
mock {
println 'Running in custom "mock" mode.'
}
}
以这种方式致电Grails:grails -Dgrails.env=mock run-app
从mrhaki看一下this blogpost。
答案 1 :(得分:1)
请注意,如果您定义了多个自定义环境,则可能会出现问题。我正在使用Grails 2.4.4。如果我定义了mytest和myqa环境,那么两个都将由Grails执行,因为它们都是Environment.CUSTOM,这意味着一些bean定义被覆盖或配置错误!
grails.util.Environment.executeForCurrentEnvironment {
development {
println 'Running in DEV mode.'
}
mytest {
println 'This will be evaluated because it is CUSTOM'
}
myqa {
println 'This will ALSO be evaluated because it is CUSTOM. Yikes!'
}
}
我不知道这是一个错误还是设计错误。无论如何,这就是我所做的,这似乎正常工作:
switch(Environment.current.name) {
case 'development':
println 'Running in DEV mode.'
break
case 'mytest':
println 'Running in mytest mode'
break
case 'myqa':
println 'Running in myqa mode'
break
}