2010-03-04 42 views
2

我試圖在Grails應用程序中攔截方法調用(域類的afterInsert())。在我的插件的doWithDynamicMethods關閉我:在Grails/Groovy中攔截或重命名方法調用

for (dc in application.domainClasses) { 
    // What I'm basically doing is renaming method A to B 
    // and creating a new method A with its own business logic 
    // and a call to B() at the end 

    def domainClass = dc.getClazz() 
    def oldAfterInsert = domainClass.metaClass.afterInsert 
    domainClass.metaClass."afterInsert_old" = oldAfterInsert 

    dc.metaClass.afterInsert = { 
     // New afterInsert() logic here 

     // Call the old after insert 
     delegate.afterInsert_old() 
    } 

} 

但後來我得到這個錯誤:

No signature of method: static com.example.afterInsert_old() is applicable for argument types:() values: [] 

我也試圖與dc.metaClass稱它爲「afterInsert_old」 .invoke(委託,新對象[0]),但後來我得到:

Caused by: groovy.lang.MissingMethodException: No signature of method: groovy.lang.ExpandoMetaClass$ExpandoMetaProperty.invoke() is applicable for argument types: (com.example.DomainName, [Ljava.lang.Object;) values: [com.example.DomainName : 115, []] 

我在做什麼錯?我怎樣才能調用一個不帶參數的方法?

我知道AOP,也看過Grails Audit Logging插件作爲例子。但是,據我所知,它所做的是添加新的用戶創建的方法,以便在正確的時間觸發。我想自動注入我的代碼,以便用戶不必擔心任何事情,並且我不想摧毀他的原始afterInsert()(或任何方法)實現。

另外,我想爲暴露的服務方法做同樣的事情,以便爲它們注入安全性。但是,從我讀過的內容來看,由於BeanWrapper並不會工作,並且因爲服務總是被重新加載。有人能更好地向我解釋這一點嗎?

在此先感謝。

回答

3

我不認爲你需要重新命名舊的方法。你可以不喜歡它在this example

for (dc in application.domainClasses) { 
    // What I'm basically doing is renaming method A to B 
    // and creating a new method A with its own business logic 
    // and a call to B() at the end 
    def domainClass = dc.getClazz() 
    def savedAfterInsert = domainClass.metaClass.getMetaMethod('afterInsert', [] as Class[]) 
    domainClass.metaClass.afterInsert = { 
     // New afterInsert() logic here 

     // Call the old after insert 
     savedAfterInsert.invoke(delegate) 
    } 

} 

只要確保在getMetaMethod返回正確的方法。