Configuration in Grails is generally split across 2 areas: build configuration and runtime configuration.
Build configuration is generally done via Gradle and the build.gradle file. Runtime configuration is by default specified in YAML in the grails-app/conf/application.yml file.
自定义配置放在grails-app/conf/application.groovy 下面
例如:
my.tmp.dir = "${userHome}/.grails.tmp"
配置时可用的变量 | 控制器里面打印出来的结果 | 描述 |
---|---|---|
userHome | C:\Users\Administrator | Location of the home directory for the account that is running the Grails application. |
grailsHome | null | Location of the directory where you installed Grails. If the GRAILS_HOME environment variable is set, it is used. |
appName | @info.app.name@ | The application name as it appears in application.properties. |
appVersion | @info.app.version@ | The application version as it appears in application.properties. |
读取运行时的配置(application.yml )可用grailsApplication对象。 use the grailsApplication object, which is available as a variable in controllers and tag libraries:
class MyController {
def hello() {
def recipient = grailsApplication.config.getProperty('foo.bar.hello')
render "Hello ${recipient}"
}
}
The config property of the grailsApplication object is an instance of the Config interface and provides a number of useful methods to read the configuration of the application.
Notice that the Config instance is a merged configuration based on Spring’s PropertySource concept and reads configuration from the environment, system properties and the local application configuration merging them into a single object.
GrailsApplication can be easily injected into services and other Grails artifacts:
import grails.core.*
class MyService {
GrailsApplication grailsApplication
String greeting() {
def recipient = grailsApplication.config.getProperty('foo.bar.hello') //或者可以写成: grailsApplication.config.foo.bar.hello
return "Hello ${recipient}" }
}
Finally, you can also use Spring’s Value annotation to inject configuration values:
import org.springframework.beans.factory.annotation.*
class MyController {
/*
注意:()中接受的是String类型。里面只能使用'',不能用"" otherwise it is interpreted as a GString not a Spring expression.
*/
@Value('${foo.bar.hello}')
String recipient
def hello() {
render "Hello ${recipient}"
}
}
In Groovy code you must use single quotes around the string for the value of the Value annotation otherwise it is interpreted as a GString not a Spring expression.As you can see, when accessing configuration settings you use the same dot notation as when you define them.