在我的Grails应用程序我已经安装了Quartz插件。我想拦截调用每个Quartz作业类'execute
方法的调用,以便在调用execute
方法之前执行某些操作(类似于建议之前的AOP)。Groovy的方法拦截
目前,我试图做从doWithDynamicMethods
关闭另一个插件的这种拦截,如下图所示:
def doWithDynamicMethods = { ctx ->
// get all the job classes
application.getArtefacts("Job").each { klass ->
MetaClass jobMetaClass = klass.clazz.metaClass
// intercept the methods of the job classes
jobMetaClass.invokeMethod = { String name, Object args ->
// do something before invoking the called method
if (name == "execute") {
println "this should happen before execute()"
}
// now call the method that was originally invoked
def validMethod = jobMetaClass.getMetaMethod(name, args)
if (validMethod != null) {
validMethod.invoke(delegate, args)
} else {
jobMetaClass.invokeMissingMethod(delegate, name, args)
}
}
}
}
所以,对于一个工作,如
class TestJob {
static triggers = {
simple repeatInterval: 5000l // execute job once in 5 seconds
}
def execute() {
"execute called"
}
}
它应该打印:
这应该发生在执行前()
执行c alled
但我的方法拦截企图似乎没有任何效果,相反,它只是打印:
执行所称为
也许问题的原因是this Groovy bug?尽管Job类没有明确实现接口,但我怀疑这是由于某些Groovy voodoo而隐含的,它们是这个接口的实例。
如果确实这个错误是我的问题的原因,有另一种方式,我可以“方法拦截之前”吗?
我以为你认识到AOP的方法,但想要替代它。 :) – dmahapatro