编程开源技术交流,分享技术与知识

网站首页 > 开源技术 正文

Grails指南10-配置之基础配置

wxchong 2024-06-24 20:03:06 开源技术 11 ℃ 0 评论

Grails的配置大致分为两类:一类是系统构建配置,另一类是运行时配置。

系统构建配置,build.gradle文件,默认借助Gradle构建工具完成网站的构建。

运行时配置,grails-app/conf/application.yml文件,默认使用YAML数据格式进行配置。

注意:关于运行时配置,你也可以使用Grails2.0的风格,具体实现方法是新建一个文件grails-app/conf/application.groovy,如果有内容,先清空然后配置即可。顺便说一句,在这种风格下你依然可以使用某些关键字,如userHome、grailsHome、appName、appVersion等,具体使用方法如my.tmp.dir = "${userHome}/.grails/tmp"。

好,回到我们的主线上来。如果你想要在控制器及标签库中读取这些配置,那么该怎么做?

class MyController {

def test() {

def dir = grailsApplication.config.getProperty("my.tmp.dir")

render "缓存目录:${dir}"

}

}

访问地址及结果如下:

http://localhost:8080/my/test

缓存目录:C:\Users\Administrator/.grails/tmp

附加内容,getProperty的特殊用法举例:

//接收整型参数'foo.bar.max.hellos',即指定参数类型为整形。'foo.bar.max.hellos'值存在时,使用其自身值,否则返回整型5

grailsApplication.config.getProperty('foo.bar.max.hellos', Integer, 5)

//接收字符型参数'foo.bar.greeting',即使用默认参数类型(字符型)。'foo.bar.greeting'值存在时,使用其自身值,否则返回字符串"Hello"

grailsApplication.config.getProperty('foo.bar.greeting', "Hello")

此外,如果你想在事务层中使用grailsApplication,你可以通过以下方法去实现:

import grails.core.*

class MyService {

GrailsApplication grailsApplication //依赖注入

def test() {

def dir = grailsApplication.config.getProperty("my.tmp.dir")

return "缓存目录:${dir}"

}

}

顺便说一下,事务的使用方法:

class MyController {

def myService //依赖注入

def index() {

render myService.test()

}

def test() {

def dir = grailsApplication.config.getProperty("my.tmp.dir")

render "缓存目录:${dir}"

}

}

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表