Interceptor 可以對方法進行攔截,並提供機會在方法的前後添加切面代碼,實現 AOP 的核心目標。Interceptor 接口僅僅定義了壹個方法 public void intercept(Invocation inv)。以下是簡單示例:
public?class?DemoInterceptor?implements?Interceptor?{public?void?intercept(Invocation?inv)?{
try?{
inv.invoke();
Render?r?=?inv.getController().getRender();
?if?(r?instanceof?JsonRender)?{
?String?JsonText?=?((JsonRender)r).getJsonText();
//?JsonText?處理
?}
}?catch?(Exception?e)?{
//異常處理
}?
}
}
以上代碼中的 DemoInterceptor 將攔截目標方法,並且在目標方法調用前後向控制臺輸出文本。inv.invoke() 這壹行代碼是對目標方法的調用,在這壹行代碼的前後插入切面代碼可以很方便地實現AOP。
註意:必須調用 inv.invoke() 方法,才能將當前調用傳遞到後續的 Interceptor 與 Action。
--3.4版本