Grails 闭包的方面(-like)函数
在Grails中(至少在当前版本2.2之前),taglib是闭包。对于某些taglib闭包,我想使用一些“环绕”类型的建议/将闭包包装在拦截器中 换句话说,假设Grails文档中有一个直接的标记库:Grails 闭包的方面(-like)函数,grails,groovy,aop,taglib,Grails,Groovy,Aop,Taglib,在Grails中(至少在当前版本2.2之前),taglib是闭包。对于某些taglib闭包,我想使用一些“环绕”类型的建议/将闭包包装在拦截器中 换句话说,假设Grails文档中有一个直接的标记库: class SimpleTagLib { def emoticon = { attrs, body -> out << body() << (attrs.happy == 'true' ? " :-)" : " :-(") } } 类Simpl
class SimpleTagLib {
def emoticon = { attrs, body ->
out << body() << (attrs.happy == 'true' ? " :-)" : " :-(")
}
}
类SimpleTagLib{
def emoticon={attrs,body->
out我写了一些类似的东西,我把它作为一个公共闭包放在一个类别中,然后加入到服务中:
// TimingCategory.groovy
/**
* Provides common AOP timing functionality to Services which mixin this category.
*/
class TimingCategory {
static Closure timer = { String label = "The call", Closure closure ->
Long start = System.currentTimeMillis()
def result = closure.call()
Long end = System.currentTimeMillis()
Long duration = end - start
log.warn "${label} took ${duration} ms"
return result
}
}
在其他类中,您只需引用计时器
闭包:
@Mixin(TimingCategory)
public class WhateverService {
public String doSomeWork() {
timer "Doing a lot of work", {
1000.times { doSomething() }
someMethodWithAStringReturnValue()
}
}
}
这将为您提供日志输出“WARN:doSomeWork”nn ms“,并返回内部闭包的值作为doSomeWork
方法的返回值
对于您的taglib实例,只需将包装出来,getProperty
或missingProperty
中的一个环绕切入点怎么样?不确定grails是如何获得闭包属性的可能更简单的方法是用元类更改闭包的行为。请向grails JIRA添加JIRA功能请求。这是一个Grails中缺少功能。有关另一个用例(taglib缓存),请参阅。
timer "Writing an emoticon", {
// your code
}
class TimedTagLib {
static namespace = "timer"
def timedTag = { attrs, body ->
timer "Executing the timed tag", {
out << body()
}
}
}
<timer:timedTag><g:emoticon whatever="something">Text</g:emoticon></timer:timedTag>
// TimedTagLib.groovy
@Mixin(TimingCategory)
class TimedTagLib {
static namespace = "timer"
def timedTag = { attrs, body ->
def duration = returnTimer "Printing the timed tag", {
out << body()
}
out << "Took ${duration} ms to print"
}
}
// someView.gsp
<timer:timedTag>
<g:formatLocalDate date="${LocalDate.now()}" />
</timer:timedTag>
03/19/2013
Took 6 ms to print