Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/grails/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Grails 闭包的方面(-like)函数_Grails_Groovy_Aop_Taglib - Fatal编程技术网

Grails 闭包的方面(-like)函数

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

在Grails中(至少在当前版本2.2之前),taglib是闭包。对于某些taglib闭包,我想使用一些“环绕”类型的建议/将闭包包装在拦截器中

换句话说,假设Grails文档中有一个直接的标记库:

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