jdk动态代理在mybatis的动态代理的应用

jdk的动态代理使用方式

暂且不用管jdk的实现原理是啥,理解jdk动态代理的使用方式。

我们在使用接口时,所有interface类型的变量总是通过向上转型并指向某个实例的:UserInterface user = new UserImpl() ,那么我们想偷懒一下,有没有可能不编写实现类,直接在运行期创建某个interface的实例呢?调用接口时不用每次为该接口编写实现类,让其实现类自动生成。

jdk提供了一套动态代理的机制可以帮助我们做到。可以在运行期动态创建某个interface的实例。

我们仍然先定义了接口UserService,但是我们并不去编写实现类,而是直接通过JDK提供的一个 Proxy.newProxyInstance() 创建了一个UserService接口对象。

这种没有实现类但是在运行期动态创建了一个接口对象的方式,我们称为动态代码。JDK提供的动态创建接口对象的方式,就叫动态代理。 动态代理的核心思想 :创建需要被代理的接口,如果使用了动态代理该接口,减少了手动编写接口实现类的繁琐工作

如下通过一个jdk的动态代理demo更好的理解。

public interface UserService {
    
    
    public String select();
    public void update();
}

代理类,该代理类代理哪个接口,需要在实例化代理类的时候指定。创建了代理类,我们可以在代理类中任意创建方法。

package com.marsdl.demo.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class UserServiceJdkProxy implements InvocationHandler {
    
    
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    
    
        //根据业务需要编写实现代码,被代理的方法都要经过该方法
        System.out.println(method);
        return "nihao";
    }
}

调用被代理的接口 UserService 均会调用 UserServiceJdkProxy 类中的 invoke 方法。看到这里明白了,动态代理的好处,我们可以同意对某个接口中的所有方法的实现进行管理。

动态代理的实例化,实例化的过程中,需要指定该动态代理代理哪个接口。

import java.lang.reflect.Proxy;

public class Test {
    
    
    public static void main(String[] args) {
    
    
        UserService hello = (UserService) Proxy.newProxyInstance(
                UserService.class.getClassLoader(), // 传入ClassLoader
                new Class[]{
    
    UserService.class}, // 传入要实现的接口
                new UserServiceJdkProxy()); // 传入处理调用方法的InvocationHandler
        String result = hello.select();
        System.out.println(result);
    }
}

在运行期动态创建一个interface实例的方法如下:

  • 定义一个InvocationHandler实例,它负责实现接口的方法调用;
  • 通过Proxy.newProxyInstance()创建interface实例,它需要3个参数:使用的ClassLoader,通常就是接口类的ClassLoader
  • 需要实现的接口数组,至少需要传入一个接口进去;用来处理接口方法调用的InvocationHandler实例;将返回的Object强制转型为接口。

参考文章: 动态代理https://www.liaoxuefeng.com/wiki/1252599548343744/1264804593397984

jdk的动态代理在mybatis中的使用

dao接口与mapper.xml绑定,为其生成代理工厂

通过动态代理的样例,知道动态代理的创建方法以及动态代理存在的目的。为了能够更好的理解动态代理在实际的应用,以mybatis源码为例子,阐述我对动态代理在实际应用的理解。

通过哪种方法调用与使用到动态代理的文章,请首先阅读(必读,因为我下文在此基础上解释),JDK动态代理实现原理mybatis–动态代理实现 ,这两篇博客写的非常好,很容易阅读。

public class MapperProxyFactory<T> {
    
    

  private final Class<T> mapperInterface;
  private final Map<Method, MapperMethodInvoker> methodCache = new ConcurrentHashMap<>();

  public MapperProxyFactory(Class<T> mapperInterface) {
    
    
    this.mapperInterface = mapperInterface;
  }

  public Class<T> getMapperInterface() {
    
    
    return mapperInterface;
  }

  public Map<Method, MapperMethodInvoker> getMethodCache() {
    
    
    return methodCache;
  }

  @SuppressWarnings("unchecked")
  protected T newInstance(MapperProxy<T> mapperProxy) {
    
    
    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] {
    
     mapperInterface }, mapperProxy);
  }

  public T newInstance(SqlSession sqlSession) {
    
    
    final MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession, mapperInterface, methodCache);
    return newInstance(mapperProxy);
  }

}

MapperProxyFactory是在mapper.xml解析的时候就已经初始化,源码在 MapperRegistry的addMapper()函数中 knownMappers.put(type, new MapperProxyFactory<T>(type));

可以得到mybatis的启动过程中,为每个dao接口就绑定一个MapperProxyFactoryMapperProxyFactory 为dao接口(也可称为,这里的dao接口就是程序员开发的dao接口)的代理类工厂。 MapperProxyFactory代理类工厂的newInstance(SqlSession sqlSession) 方法在被调用过程为该dao接口生成代理类。

为dao创建代理

在使用dao操作数据库数据之前需要执行 Mapper mapper = sqlSession.getMapper(Mapper.class); 。通过调用链逐个查看下去,最后会调用 MapperProxyFactory中的newInstance方法,为mapper接口(dao接口)生成一个代理对象。

public T newInstance(SqlSession sqlSession) {
    
    
 final MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession, mapperInterface, methodCache);
 return newInstance(mapperProxy);
}

我们查看MapperProxy是什么,看到这里MapperProxy是实现InvocationHandler接口,根据jdk的动态代理使用方式介绍,我们知道了这个就是jdk的动态代理方式。

public class MapperProxy<T> implements InvocationHandler, Serializable {
    
    
  
  ... 省略部分代码
  
  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    
    
    try {
    
    
      if (Object.class.equals(method.getDeclaringClass())) {
    
    
        return method.invoke(this, args);
      } else {
    
    
        return cachedInvoker(method).invoke(proxy, method, args, sqlSession);
      }
    } catch (Throwable t) {
    
    
      throw ExceptionUtil.unwrapThrowable(t);
    }
  }

使用了jdk动态代理那么也就是符合jdk动态代理的核心思想:

动态代理的核心思想 :创建需要被代理的接口,如果使用了动态代理该接口,减少了手动编写接口实现类的繁琐工作

mybatis是给mapper接口(dao接口)动态生成代理,减少dao接口手动编写dao接口实现类的繁琐工作,这是一件非常好的工作。

这里我们明白了为什么mybatis使用动态代理,因此我们不再需要手动编写dao接口的实现类,mybatis为我们接口自动生成代理实现。

Mapper mapper = sqlSession.getMapper(Mapper.class);
User user = mapper.getUser(1);

mybatis实现的代理实现是: mybatis使得接口与mapper.xml中的sql语句关联,在如上的调用代码,mapper调用mapper接口(dao接口)getUser时,就是调用mybatis为我们生成的代理类对象MapperProxy。然后代理类MapperProxy对象通过invoke方法 sqlSession调用

代理带来不同的方法

这里有个疑问,如下图所示某个dao接口有很多的方法(方法1,方法2,方法N),mybatis代理类如何实现只有invoke方法情况下代理不同的代理类。
在这里插入图片描述

//这里会拦截Mapper接口的所有方法 
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    
    
  try {
    
    
    //如果是Object中定义的方法,直接执行。如toString(),hashCode()if (Object.class.equals(method.getDeclaringClass())) {
    
    
      return method.invoke(this, args);
    } else {
    
    
     //其他Mapper接口定义的方法交由mapperMethod来执行
      return cachedInvoker(method).invoke(proxy, method, args, sqlSession);
    }
  } catch (Throwable t) {
    
    
    throw ExceptionUtil.unwrapThrowable(t);
  }
}

查看源码的MapperProxy代理类中的invoke方法,cachedInvoker(method).invoke(proxy, method, args, sqlSession); 源码中,再次点击调用链,会查看到如下MapperMethod类中的execute方法,execute是dao接口的代理类执行数据库操作的执行入口,execute方法会根据SqlCommand中type属性选择不同的sqlSession方法进行处理。

/**
   * 这个方法是对SqlSession的包装,对应insert、delete、update、select四种操作
   */
public Object execute(SqlSession sqlSession, Object[] args) {
    
    
    Object result;//返回结果
   //INSERT操作
    if (SqlCommandType.INSERT == command.getType()) {
    
    
      Object param = method.convertArgsToSqlCommandParam(args);
      //调用sqlSession的insert方法
      result = rowCountResult(sqlSession.insert(command.getName(), param));
    } else if (SqlCommandType.UPDATE == command.getType()) {
    
    
      //UPDATE操作 同上
      Object param = method.convertArgsToSqlCommandParam(args);
      result = rowCountResult(sqlSession.update(command.getName(), param));
    } else if (SqlCommandType.DELETE == command.getType()) {
    
    
      //DELETE操作 同上
      Object param = method.convertArgsToSqlCommandParam(args);
      result = rowCountResult(sqlSession.delete(command.getName(), param));
    } else if (SqlCommandType.SELECT == command.getType()) {
    
    
      //如果返回void 并且参数有resultHandler  ,则调用 void select(String statement, Object parameter, ResultHandler handler);方法
      if (method.returnsVoid() && method.hasResultHandler()) {
    
    
        executeWithResultHandler(sqlSession, args);
        result = null;
      } else if (method.returnsMany()) {
    
    
        //如果返回多行结果,executeForMany这个方法调用 <E> List<E> selectList(String statement, Object parameter);
        result = executeForMany(sqlSession, args);
      } else if (method.returnsMap()) {
    
    
        //如果返回类型是MAP 则调用executeForMap方法
        result = executeForMap(sqlSession, args);
      } else {
    
    
        //否则就是查询单个对象
        Object param = method.convertArgsToSqlCommandParam(args);
        result = sqlSession.selectOne(command.getName(), param);
      }
    } else {
    
    
        //接口方法没有和sql命令绑定
        throw new BindingException("Unknown execution method for: " + command.getName());
    }
    //如果返回值为空 并且方法返回值类型是基础类型 并且不是void 则抛出异常
    if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) {
    
    
      throw new BindingException("Mapper method '" + command.getName()
          + " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ").");
    }
    return result;
  }

这里我们理解了mybatis的MapperProxy代理类如何通过一个invoke方法代理带来不同的方法,通过SqlCommand中的type来指定代理的方法是增删改查等中的某一个,那么sqlSession就知道应该使用不同的方法处理了。

其他网上一般会说,绕来绕去又回到是sqlSession处理了,其实这样说不好,有点模糊动态代理在mybatis存在的意义,让人感觉到动态代理故意让mybatis显得繁琐。

之所以mybatis使用了动态代理,是因为动态代理加入只需要我们编写接口与sql语句就可以了,不需要我们再实现dao接口然后再手动使用sqlSession调用不同的方法;动态代理的应用减少了我们工作负担,将精力集中在sql的编写上面。

鉴于笔者水平有限,可能存在很多错误之处,希望能够指出,谢谢

猜你喜欢

转载自blog.csdn.net/Hello_Ray/article/details/112347771