2012-04-03 25 views
0

我已經編寫了一個MethodInterceptor來收集基於Spring的應用程序的性能指標。基本上所有的服務類和一些DAO將通過這個攔截器。我的問題是,有沒有辦法在運行時禁用此攔截器,以保存由於通過反射調用而導致的任何性能影響。如何在運行時禁用方法攔截器

回答

0

我不認爲在現代JVM中使用反射會有明顯的性能損失。另外我不認爲有一種簡單的方法來動態禁用攔截器。

如果你在攔截器中做了一些你想避免的非平凡處理,最簡單的方法可能是在攔截器中檢查一些可以在運行時設置的屬性。像這樣的東西應該工作:

public abstract class BaseInterceptor implements MethodInterceptor { 
    private boolean bypass; 

    /** 
    * If set to true all processing defined in child class will be bypassed 
    * This could be useful if advice should have flexibility of being turned ON/OFF via config file 
    * */ 
    public void setBypass(boolean bypass) { 
    this.bypass = bypass; 
    } 

    public final Object invoke(MethodInvocation methodInvocation) throws Throwable { 
     if (bypass) { 
     return methodInvocation.proceed(); 
     } 
     this.logger.debug(">>>"); 
     return onInvoke(methodInvocation); 
    } 

    protected abstract Object onInvoke(MethodInvocation methodInvocation) throws Throwable; 
} 

在Spring上下文文件,你可以設置基於Java的系統屬性「旁路」屬性,例如,或者從配置文件讀取它。

+0

是否通過反射調用methodInvocation.proceed()? – user325643 2012-04-04 07:31:11

+0

這只是在答案中看到我對反思績效的評論。是什麼讓你認爲反射在你的情況下導致性能問題?你有任何測量來確認嗎? – maximdim 2012-04-04 11:57:17