mybatis攔截器的作用與簡單示例
- 攔截器的機理
- 攔截器的作用
- 攔截器的實作
- 攔截器的原理
攔截器的機理
MyBatis 允許你在已映射語句執行過程中的某一點進行攔截調用。預設情況下,MyBatis 允許使用插件來攔截的方法調用包括:
在mybatis的mybatis-config.xml檔案中配置plugins(插件),能夠攔截四個類的部分方法。
-
Executor (update, query, flushStatements, commit, rollback,
getTransaction, close, isClosed)
- ParameterHandler (getParameterObject, setParameters)
- ResultSetHandler (handleResultSets, handleOutputParameters)
- StatementHandler (prepare, parameterize, batch, update, query)
攔截器的作用
攔截器可以攔截許多方法,在特定的業務中有重要的作用。例如,應用可以攔截使用者的請求并判斷是否是合法請求。,應用也可以攔截方法後檢查參數是否符合要求等等。
攔截器的實作
MyBatis 提供了強大機制,隻需實作 Interceptor 接口,并指定想要攔截的方法簽名即可實作攔截器的功能。
下面是攔截器的簡單示例。
@Intercepts(value = { @Signature(args = { MappedStatement.class, Object.class, RowBounds.class,
ResultHandler.class }, method = "query", type = Executor.class) })
public class MyInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
/*A*/
Object obj = invocation.proceed();
/*B*/
return obj;
}
}
invocation.proceed()的作用就是調用被攔截的方法。是以在注釋A部分的代碼運作在方法執行之前,注釋B的代碼運作在方法執行之後。
攔截器的原理
通過跟斷點,容易發現mybatis的SqlSession在執行selectList()的時候執行executor的query()方法。而executor.query()中調用了Plugin的invoke()方法。
Plugin擁有私有屬性interceptor,通過反射的方法獲得其實作類的對象,并
在Plugin的invoke()方法中通過調用了interceptor.intercept()方法進而調用了重寫的MyInterceptor.intercept()。通過java反射機制與接口回調,mybtis成功地實作了攔截器。