在我的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