作者:yhjyumi的专栏

数据权限实现(Mybatis拦截器+JSqlParser)

Mybatis的拦截器实现机制,使用的是JDK的InvocationHandler.

当我们调用ParameterHandler,ResultSetHandler,StatementHandler,Executor的对象的时候,
实际上使用的是Plugin这个代理类的对象,这个类实现了InvocationHandler接口.
接下来我们就知道了,在调用上述被代理类的方法的时候,就会执行Plugin的invoke方法.
Plugin在invoke方法中根据@Intercepts的配置信息(方法名,参数等)动态判断是否需要拦截该方法.
再然后使用需要拦截的方法Method封装成Invocation,并调用Interceptor的proceed方法.
这样我们就达到了拦截目标方法的结果.
例如Executor的执行大概是这样的流程:
拦截器代理类对象->拦截器->目标方法
Executor->Plugin->Interceptor->Invocation
Executor.Method->Plugin.invoke->Interceptor.intercept->Invocation.proceed->method.invoke


注解
@Intercepts 在实现Interceptor接口的类声明,使该类注册成为拦截器
Signature[] value//定义需要拦截哪些类,哪些方法
@Signature 定义哪些类(4种),方法,参数需要被拦截
Class<?> type()//ParameterHandler,ResultSetHandler,StatementHandler,Executor
String method()//
Class<?>[] args()// 接口
Interceptor 实现拦截器的接口 类
InterceptorChain 拦截器链,保存了Mybatis配置的所有拦截器,保存在Configuration
List<Interceptor> interceptors//拦截器 Invocation 类方法的一个封装,在拦截器中就是被调用的目标方法
Object target//调用的对象
Method method//调用的方法
Object[] args//参数 Plugin 插件,其实就是ParameterHandler,ResultSetHandler,StatementHandler,Executor的代理类(Mybatis使用的JDK代理实现拦截器),实现了InvocationHandler接口
Object target//被代理的目标对象
Interceptor interceptor//拦截器
Map<Class<?>, Set<Method>> signatureMap//接口需要拦截的方法(一对多,每个接口对应多个方法)
//
wrap(Object target, Interceptor interceptor)//把拦截器对象封装成Plugin代理对象.
invoke(Object proxy, Method method, Object[] args)//

使用例子

1.写一个类,并且实现Interceptor接口
2.在上述类使用@Intercepts注解,配置拦截信息
3.在配置文件配置插件

@Intercepts({ @Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class,
RowBounds.class, ResultHandler.class }) })
public class MyInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
// TODO Auto-generated method stub }
}

配置文件加入

<plugins>
<plugin interceptor="weber.mybatis.plugin.MyInterceptor" />
</plugins>
  1. public static void main(String[] args) throws IOException {
  2. String resource = "conf.xml";
  3. InputStream is = Test1.class.getClassLoader().getResourceAsStream(resource);
  4. SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
  5. SqlSession session = sessionFactory.openSession();
  6. // User user = session.selectOne("weber.mybatis.mapper.getUser", 1);
  7. User userObj = new User();
  8. userObj.setId(123);
  9. session.selectList("weber.mybatis.mapper.searchByUser", userObj);
  10. // UserMapper mapper = session.getMapper(UserMapper.class);
  11. // mapper.selectAll();
  12. // System.out.println(user);
  13. }

开启debug模式,我们将看到Plugin是如何实现代理的.

当代码执行到下图红色部分的时候

将直接跳到下图!所以,我们此时的executor不是CachingExecutor对象,而是Plugin代理对象.

此时的method,就是被调用的目标方法如下:

最后附上源码注释

  1. /**
  2. * @author Clinton Begin
  3. */
  4. //Plugin是JDK动态代理类
  5. public class Plugin implements InvocationHandler {
  6. private Object target;//目标对象(ParameterHandler,ResultSetHandler,StatementHandler,Executor)
  7. private Interceptor interceptor;//被代理的拦截器
  8. //目标类需要拦截的方法缓存.因为一个拦截器可以拦截多个类,一个类可以拦截多个方法.
  9. //所以用Map + Set的数据结构存储
  10. private Map<Class<?>, Set<Method>> signatureMap;//保存每个拦截器的@signature的配置信息
  11. private Plugin(Object target, Interceptor interceptor, Map<Class<?>, Set<Method>> signatureMap) {
  12. this.target = target;
  13. this.interceptor = interceptor;
  14. this.signatureMap = signatureMap;
  15. }
  16. //把目标对象和拦截器封装成Plugin代理类实例.
  17. public static Object wrap(Object target, Interceptor interceptor) {
  18. Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);//获取拦截器的拦截信息(需要拦截的类和方法)
  19. Class<?> type = target.getClass();
  20. Class<?>[] interfaces = getAllInterfaces(type, signatureMap);//Proxy代理只能代理接口
  21. if (interfaces.length > 0) {
  22. return Proxy.newProxyInstance(
  23. type.getClassLoader(),
  24. interfaces,
  25. new Plugin(target, interceptor, signatureMap));//Plugin作为代理类,但是实际业务是由Interceptor拦截器完成的.
  26. }
  27. return target;
  28. }
  29. @Override
  30. //proxy,类代理的对象,例如CachingExecutor对象
  31. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  32. try {//从这里代码看到,会拦截所有的Executor方法,动态的去判断拦截器要不要去拦截.所以要小心使用拦截器,会影响性能.
  33. Set<Method> methods = signatureMap.get(method.getDeclaringClass());
  34. if (methods != null && methods.contains(method)) {
  35. //Invocation是目标对象,目标对象需要拦截的方法,我拦截方法的参数的封装.
  36. return interceptor.intercept(new Invocation(target, method, args));//调用拦截器实现拦截
  37. }
  38. return method.invoke(target, args);//不需要拦截的方法直接放行
  39. } catch (Exception e) {
  40. throw ExceptionUtil.unwrapThrowable(e);
  41. }
  42. }
  43. private static Map<Class<?>, Set<Method>> getSignatureMap(Interceptor interceptor) {
  44. Intercepts interceptsAnnotation = interceptor.getClass().getAnnotation(Intercepts.class);//获取拦截器注解@Signature
  45. // issue #251
  46. if (interceptsAnnotation == null) {
  47. throw new PluginException("No @Intercepts annotation was found in interceptor " + interceptor.getClass().getName());
  48. }
  49. Signature[] sigs = interceptsAnnotation.value();//一个Signature表示一个拦截类型
  50. //保存需要拦截类的信息,class作为key, 需要拦截类的方法作为value集合Set保存.一个拦截器可以拦截一个类中多个方法
  51. Map<Class<?>, Set<Method>> signatureMap = new HashMap<Class<?>, Set<Method>>();
  52. for (Signature sig : sigs) {
  53. Set<Method> methods = signatureMap.get(sig.type());
  54. if (methods == null) {
  55. methods = new HashSet<Method>();
  56. signatureMap.put(sig.type(), methods);
  57. }
  58. try {
  59. Method method = sig.type().getMethod(sig.method(), sig.args());//获取需要拦截的方法
  60. methods.add(method);
  61. } catch (NoSuchMethodException e) {
  62. throw new PluginException("Could not find method on " + sig.type() + " named " + sig.method() + ". Cause: " + e, e);
  63. }
  64. }
  65. return signatureMap;
  66. }
  67. private static Class<?>[] getAllInterfaces(Class<?> type, Map<Class<?>, Set<Method>> signatureMap) {
  68. Set<Class<?>> interfaces = new HashSet<Class<?>>();
  69. while (type != null) {
  70. for (Class<?> c : type.getInterfaces()) {
  71. if (signatureMap.containsKey(c)) {
  72. interfaces.add(c);
  73. }
  74. }
  75. type = type.getSuperclass();
  76. }
  77. return interfaces.toArray(new Class<?>[interfaces.size()]);
  78. }
  79. }

 

  1. /**
  2. * @author Clinton Begin
  3. */
  4. //InterceptorChain里保存了所有的拦截器,它在mybatis初始化的时候创建。存在Configuration中
  5. public class InterceptorChain {
  6. private final List<Interceptor> interceptors = new ArrayList<Interceptor>();
  7. //每一个拦截器对目标类都进行一次代理(也就是会出现代理的代理的代理.....有点拗口)
  8. public Object pluginAll(Object target) {
  9. for (Interceptor interceptor : interceptors) {
  10. target = interceptor.plugin(target);
  11. }
  12. return target;
  13. }
  14. public void addInterceptor(Interceptor interceptor) {
  15. interceptors.add(interceptor);
  16. }
  17. public List<Interceptor> getInterceptors() {
  18. return Collections.unmodifiableList(interceptors);
  19. }
  20. }

 

    1. /**
    2. * @author Clinton Begin
    3. */
    4. public interface Interceptor {
    5. Object intercept(Invocation invocation) throws Throwable;//拦截方法,在这里处理拦截器的业务逻辑
    6. Object plugin(Object target);//把目标对象封装成Plugin对象
    7. void setProperties(Properties properties);
    8. }

最新文章

  1. flask笔记3-模板
  2. XML与JSON的对比
  3. 配置NTP时间服务器
  4. 关于Opengl中将24位BMP图片加入一个alpha通道并实现透明的问题
  5. Allegro绘制PCB流程
  6. ubuntu 修复 could not open file &#39;/etc/apt/sources.list&#39;
  7. HBase 快照操作
  8. 借助Chrome和插件爬取数据
  9. SpringBoot 整合 apollo
  10. Docker启动的问题解决笔记
  11. 分享:五个非常有用的WP插件
  12. MySQL设置global变量和session变量
  13. 新萌渗透测试入门DVWA 教程2:DWVA 的配置和暴力破解靶机
  14. linux 终端命令行的快捷键列表
  15. 原生js实现九宫格,全解析
  16. (网络编程)socketserver模块服务端实现并发
  17. sqlalchemy根据数据库结构生成映射的实体
  18. KM匹配板子
  19. HTTP协议的请求与响应和CSS属性和定位
  20. Mybatis三剑客之mybatis-generator配置

热门文章

  1. 如何克服社交恐惧症?zz
  2. new pdo 连接很慢的原因和解决办法
  3. SQL 十位随机数(大小写字母+数据)
  4. 【AtCoder】ARC067
  5. Reactor 线程模型以及在netty中的应用
  6. windows下安装mongoDB(zip版)
  7. Java多线程(八):ReentrantReadWriteLock
  8. Kirinriki 2017多校
  9. MVC和WebApi中设置Area中的页为首页
  10. sql server的循环语句