@(MyBatis)[Plugin]

MyBatis源码分析——Plugin原理

Plugin原理

Plugin的实现采用了Java的动态代理,应用了责任链设计模式

InterceptorChain

拦截器链,用于保存从配置文件解析后的所有拦截器

插件链的创建

在Configuration解析配置文件的时候,XMLConfigBuilder.parseConfiguration中会调用pluginElement解析插件信息并实例化后,保存到插件链中

// /configuration/plugins节点
private void pluginElement(XNode parent) throws Exception {
if (parent != null) {
// 获取所有的插件定义
for (XNode child : parent.getChildren()) {
String interceptor = child.getStringAttribute("interceptor");
Properties properties = child.getChildrenAsProperties();
// 反射,实例化插件
Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).newInstance();
interceptorInstance.setProperties(properties);
// 保存到插件链中
configuration.addInterceptor(interceptorInstance);
}
}
}
// Configuration.addInterceptor
public void addInterceptor(Interceptor interceptor) {
interceptorChain.addInterceptor(interceptor);
} public class InterceptorChain {
// 所有拦截器实例
private final List<Interceptor> interceptors = new ArrayList<Interceptor>(); public Object pluginAll(Object target) {
for (Interceptor interceptor : interceptors) {
target = interceptor.plugin(target);
}
return target;
} public void addInterceptor(Interceptor interceptor) {
interceptors.add(interceptor);
} public List<Interceptor> getInterceptors() {
return Collections.unmodifiableList(interceptors);
} }

插件拦截

在MyBatis中,只能拦截四种接口的实现类:

  • Executor

  • ParameterHandler

  • ResultSetHandler

  • StatementHandler

    每种类型的拦截方式都是一样的,这里取executor为例:

    在创建SqlSession的时候,会需要创建Executor实现类,在创建时,会调用插件链的加载插件功能:executor = (Executor) interceptorChain.pluginAll(executor);,该方法会形成一个调用链。

        // 依次调用每个插件的plugin方法,如果该插件无需拦截target,则直接返回target
    public Object pluginAll(Object target) {
    for (Interceptor interceptor : interceptors) {
    target = interceptor.plugin(target);
    }
    return target;
    }
Plugin

插件代理的实现,这里应用了Java Dynamic Proxy

	public class Plugin implements InvocationHandler {
// 需要被代理的实例
private Object target;
// 拦截器实例
private Interceptor interceptor;
// 拦截器需要拦截的方法摘要,这里Class键为Executor等上述的四个
// 值为需要被拦截的方法
private Map<Class<?>, Set<Method>> signatureMap; // 此类不能直接创建,需要通过静态方法wrap来创建代理类
private Plugin(Object target, Interceptor interceptor,
Map<Class<?>, Set<Method>> signatureMap) {
this.target = target;
this.interceptor = interceptor;
this.signatureMap = signatureMap;
} public static Object wrap(Object target, Interceptor interceptor) {
Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
Class<?> type = target.getClass();
// 获取需要被代理类的所有待拦截的接口
Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
if (interfaces.length > 0) {
// 创建代理类
return Proxy.newProxyInstance(type.getClassLoader(), interfaces,
new Plugin(target, interceptor, signatureMap));
}
// 没有需要拦截的方法,直接返回原实例
return target;
} // 在代理类中调用
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
try {
Set<Method> methods = signatureMap.get(method.getDeclaringClass());
// 判断是否为待拦截方法,这里为动态判断,所有在拦截器多的时候,会影响性能
if (methods != null && methods.contains(method)) {
return interceptor.intercept(new Invocation(target, method,
args));
}
return method.invoke(target, args);
} catch (Exception e) {
throw ExceptionUtil.unwrapThrowable(e);
}
}
// 获取需要被拦截的方法摘要
private static Map<Class<?>, Set<Method>> getSignatureMap(
Interceptor interceptor) {
// 先获取拦截器实现类上的注解,提取需要被拦截的方法
/* 注解示例:@Intercepts(value={@Signature(args={Void.class},method="query",type=Void.class)})*/
Intercepts interceptsAnnotation = interceptor.getClass().getAnnotation(
Intercepts.class);
if (interceptsAnnotation == null) { // issue #251
throw new PluginException(
"No @Intercepts annotation was found in interceptor "
+ interceptor.getClass().getName());
}
Signature[] sigs = interceptsAnnotation.value();
Map<Class<?>, Set<Method>> signatureMap = new HashMap<Class<?>, Set<Method>>();
for (Signature sig : sigs) {
Set<Method> methods = signatureMap.get(sig.type());
if (methods == null) {
methods = new HashSet<Method>();
signatureMap.put(sig.type(), methods);
}
try {
// 根据方法名以及参数获取待拦截方法
Method method = sig.type().getMethod(sig.method(), sig.args());
methods.add(method);
} catch (NoSuchMethodException e) {
throw new PluginException("Could not find method on "
+ sig.type() + " named " + sig.method() + ". Cause: "
+ e, e);
}
}
return signatureMap;
} private static Class<?>[] getAllInterfaces(Class<?> type,
Map<Class<?>, Set<Method>> signatureMap) {
Set<Class<?>> interfaces = new HashSet<Class<?>>();
while (type != null) {
for (Class<?> c : type.getInterfaces()) {
if (signatureMap.containsKey(c)) {
interfaces.add(c);
}
}
type = type.getSuperclass();
}
return interfaces.toArray(new Class<?>[interfaces.size()]);
}
}

示例:

插件配置

在mybatis.xml配置文件:

<plugins>
<plugin interceptor="com.jabnih.analysis.mybatis.interceptor.InterceptorDemo1"/>
<plugin interceptor="com.jabnih.analysis.mybatis.interceptor.InterceptorDemo2"/>
</plugins>

插件实现

@Intercepts(value={@Signature(args={MappedStatement.class,Object.class},method="update",type=Executor.class)})
public class InterceptorDemo1 implements Interceptor {
private Logger logger = LoggerFactory.getLogger(InterceptorDemo1.class);
@Override
public Object intercept(Invocation invocation) throws Throwable {
logger.debug(InterceptorDemo1.class.getName());
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
}
} @Intercepts(value={@Signature(args={MappedStatement.class,Object.class},method="update",type=Executor.class)})
public class InterceptorDemo2 implements Interceptor {
private Logger logger = LoggerFactory.getLogger(InterceptorDemo2.class);
@Override
public Object intercept(Invocation invocation) throws Throwable {
logger.debug(InterceptorDemo2.class.getName());
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
}
}

main方法

public static void main(String args[]) throws Exception {

	String resource = "mybatis.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession session = sqlSessionFactory.openSession(); ProductMapper productMapper = session.getMapper(ProductMapper.class); productMapper.updatePriceById("ANV01", BigDecimal.valueOf(6.99));
}

输出结果

2016-07-09 16:59:00 [DEBUG]-[Thread: main]-[com.jabnih.analysis.mybatis.interceptor.InterceptorDemo2.intercept()]:
com.jabnih.analysis.mybatis.interceptor.InterceptorDemo2 2016-07-09 16:59:00 [DEBUG]-[Thread: main]-[com.jabnih.analysis.mybatis.interceptor.InterceptorDemo1.intercept()]:
com.jabnih.analysis.mybatis.interceptor.InterceptorDemo1

示例的调用序列图

图片太大,可能需要另开一个页面单独看

MyBatis源码分析(2)—— Plugin原理的更多相关文章

  1. MyBatis源码分析(各组件关系+底层原理

    MyBatis源码分析MyBatis流程图 下面将结合代码具体分析. MyBatis具体代码分析 SqlSessionFactoryBuilder根据XML文件流,或者Configuration类实例 ...

  2. Mybatis源码分析--关联表查询及延迟加载原理(二)

    在上一篇博客Mybatis源码分析--关联表查询及延迟加载(一)中我们简单介绍了Mybatis的延迟加载的编程,接下来我们通过分析源码来分析一下Mybatis延迟加载的实现原理. 其实简单来说Myba ...

  3. MyBatis 源码分析 - 缓存原理

    1.简介 在 Web 应用中,缓存是必不可少的组件.通常我们都会用 Redis 或 memcached 等缓存中间件,拦截大量奔向数据库的请求,减轻数据库压力.作为一个重要的组件,MyBatis 自然 ...

  4. Mybatis源码分析之Cache二级缓存原理 (五)

    一:Cache类的介绍 讲解缓存之前我们需要先了解一下Cache接口以及实现MyBatis定义了一个org.apache.ibatis.cache.Cache接口作为其Cache提供者的SPI(Ser ...

  5. MyBatis 源码分析 - 插件机制

    1.简介 一般情况下,开源框架都会提供插件或其他形式的拓展点,供开发者自行拓展.这样的好处是显而易见的,一是增加了框架的灵活性.二是开发者可以结合实际需求,对框架进行拓展,使其能够更好的工作.以 My ...

  6. MyBatis 源码分析 - 配置文件解析过程

    * 本文速览 由于本篇文章篇幅比较大,所以这里拿出一节对本文进行快速概括.本篇文章对 MyBatis 配置文件中常用配置的解析过程进行了较为详细的介绍和分析,包括但不限于settings,typeAl ...

  7. MyBatis 源码分析-项目总览

    MyBatis 源码分析-项目总览 1.概述 本文主要大致介绍一下MyBatis的项目结构.引用参考资料<MyBatis技术内幕> 此外,https://mybatis.org/mybat ...

  8. 精尽MyBatis源码分析 - 插件机制

    该系列文档是本人在学习 Mybatis 的源码过程中总结下来的,可能对读者不太友好,请结合我的源码注释(Mybatis源码分析 GitHub 地址.Mybatis-Spring 源码分析 GitHub ...

  9. 精尽MyBatis源码分析 - MyBatis-Spring 源码分析

    该系列文档是本人在学习 Mybatis 的源码过程中总结下来的,可能对读者不太友好,请结合我的源码注释(Mybatis源码分析 GitHub 地址.Mybatis-Spring 源码分析 GitHub ...

随机推荐

  1. Python基础中所出现的异常报错总结

    今天我们来探索python中大部分的异常报错 首先异常是什么,异常白话解释就是不正常,程序里面一般是指程序员输入的格式不规范,或者需求的参数类型不对应,不全等等. 打个比方很多公司年终送苹果笔记本,你 ...

  2. 理解 Glance - 每天5分钟玩转 OpenStack(20)

    OpenStack 由 Glance 提供 Image 服务. 理解 Image 要理解 Image Service 先得搞清楚什么是 Image 以及为什么要用 Image? 在传统 IT 环境下, ...

  3. x01.Weiqi.9: 点目功能

    添加点目功能,虽不中,不远也.还是先看看截图吧. 确保其可行,再看一张: 其点目结果,还是比较令人满意的.这主要得益于多遍扫描,如编译器的词法分析阶段,下面的代码可以证明: private void ...

  4. WPF Telerik TreeListView样式设计

    Telerik控件 TreeListView 修改其中样式 1.添加TreeListView控件 <telerik:RadTreeView x:Name="ObjecTreeView& ...

  5. Navicat安装详解

    本文章介绍MySql图形化操作软件Navicat的安装 属于PHP环境搭建的一部分. PHP完整配置信息请参考 http://www.cnblogs.com/azhe-style/p/php_new_ ...

  6. jni调试3(线程调试env变量问题)

    jni层调试线程死机原因 一,导致死机原因:   jni层中  线程函数中  只要添加调用env 的函数 ,,就会死机     二,解决方法 第一我们应该理解: ①(独立性) JNIEnv 是一个与线 ...

  7. windows 2003自动登录的具体步骤

    在win2003系统中,使用最多的可能就是远程操作了,关于远程操作的那些事很多用户还是有些迷茫的.如果win2003系统远程重启后,要重新登录系统十分的麻烦,如何才能实现重启后的自动登录呢?让高手告诉 ...

  8. 测试环境搭建心得 vs2008+SQL2008 PHP+APACHE+mysql Team Foundation Server2013

    大四即将结束,大学的最后一个假期,找到一份实习工作,担任测试工程师.在过年前的最后一周入职,干了一周的活儿.主要工作就是搭建测试环境. VMware 主要熟悉VMware软件,装系统基本都没什么问题. ...

  9. Struts2 JSON

    JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式 (本质是一种数据传输格式) 定义json对象 var json={"firstName" ...

  10. C#.NET 大型通用信息化系统集成快速开发平台 4.1 版本 - 主管可以看下属的数据

    主管可以看下属的数据,这个是经常用到的一个权限,不管是大公司,还是小公司都需要的功能. 通过以下2个方法,可以任意达到想要的效果了,设置简单灵活,还能递归运算下属,有时候简单好用就是硬道理. #reg ...