美团面试:为什么就能直接调用userMapper接口的方法?

开发 前端
老规矩,先上案例代码,这样大家可以更加熟悉是如何使用的,看过Mybatis系列的小伙伴,对这段代码差不多都可以背下来了。

[[361093]]

老规矩,先上案例代码,这样大家可以更加熟悉是如何使用的,看过Mybatis系列的小伙伴,对这段代码差不多都可以背下来了。

哈哈~,有点夸张吗?不夸张的,就这行代码。

  1. public class MybatisApplication { 
  2.         public static final String URL = "jdbc:mysql://localhost:3306/mblog"
  3.         public static final String USER = "root"
  4.         public static final String PASSWORD = "123456"
  5.      
  6.         public static void main(String[] args) { 
  7.             String resource = "mybatis-config.xml"
  8.             InputStream inputStream = null
  9.             SqlSession sqlSession = null
  10.             try { 
  11.                 inputStream = Resources.getResourceAsStream(resource); 
  12.                 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); 
  13.                 sqlSession = sqlSessionFactory.openSession(); 
  14.                 //今天主要这行代码 
  15.                 UserMapper userMapper = sqlSession.getMapper(UserMapper.class); 
  16.                 System.out.println(userMapper.selectById(1)); 
  17.      
  18.             } catch (Exception e) { 
  19.                 e.printStackTrace(); 
  20.             } finally { 
  21.                 try { 
  22.                     inputStream.close(); 
  23.                 } catch (IOException e) { 
  24.                     e.printStackTrace(); 
  25.                 } 
  26.                 sqlSession.close(); 
  27.             } 
  28.         } 

看源码有什么用?

通过源码的学习,我们可以收获Mybatis的核心思想和框架设计,另外还可以收获设计模式的应用。

前两篇文章我们已经Mybatis配置文件解析到获取SqlSession,下面我们来分析从SqlSession到userMapper:

  1. UserMapper userMapper = sqlSession.getMapper(UserMapper.class); 

前面那篇文章已经知道了这里的sqlSession使用的是默认实现类DefaultSqlSession。所以我们直接进入DefaultSqlSession的getMapper方法。

  1. //DefaultSqlSession中   
  2. private final Configuration configuration; 
  3. //type=UserMapper.class 
  4. @Override 
  5. public <T> T getMapper(Class<T> type) { 
  6.   return configuration.getMapper(type, this); 

这里有三个问题:

问题1:getMapper返回的是个什么对象?

上面可以看出,getMapper方法调用的是Configuration中的getMapper方法。然后我们进入Configuration中

  1. //Configuration中   
  2. protected final MapperRegistry mapperRegistry = new MapperRegistry(this); 
  3. ////type=UserMapper.class 
  4. public <T> T getMapper(Class<T> type, SqlSession sqlSession) { 
  5.     return mapperRegistry.getMapper(type, sqlSession); 

这里也没做什么,继续调用MapperRegistry中的getMapper:

  1. //MapperRegistry中 
  2. public class MapperRegistry { 
  3.   //主要是存放配置信息 
  4.   private final Configuration config; 
  5.   //MapperProxyFactory 的映射 
  6.   private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<>(); 
  7.  
  8.   //获得 Mapper Proxy 对象 
  9.   //type=UserMapper.class,session为当前会话 
  10.   public <T> T getMapper(Class<T> type, SqlSession sqlSession) { 
  11.     //这里是get,那就有add或者put 
  12.     final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type); 
  13.     if (mapperProxyFactory == null) { 
  14.       throw new BindingException("Type " + type + " is not known to the MapperRegistry."); 
  15.     } 
  16.    try { 
  17.       //创建实例 
  18.       return mapperProxyFactory.newInstance(sqlSession); 
  19.     } catch (Exception e) { 
  20.       throw new BindingException("Error getting mapper instance. Cause: " + e, e); 
  21.     } 
  22.   } 
  23.    
  24.   //解析配置文件的时候就会调用这个方法, 
  25.   //type=UserMapper.class 
  26.   public <T> void addMapper(Class<T> type) { 
  27.     // 判断 type 必须是接口,也就是说 Mapper 接口。 
  28.     if (type.isInterface()) { 
  29.         //已经添加过,则抛出 BindingException 异常 
  30.         if (hasMapper(type)) { 
  31.             throw new BindingException("Type " + type + " is already known to the MapperRegistry."); 
  32.         } 
  33.         boolean loadCompleted = false
  34.         try { 
  35.             //添加到 knownMappers 中 
  36.             knownMappers.put(type, new MapperProxyFactory<>(type)); 
  37.             //创建 MapperAnnotationBuilder 对象,解析 Mapper 的注解配置 
  38.             MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type); 
  39.             parser.parse(); 
  40.             //标记加载完成 
  41.             loadCompleted = true
  42.         } finally { 
  43.             //若加载未完成,从 knownMappers 中移除 
  44.             if (!loadCompleted) { 
  45.                 knownMappers.remove(type); 
  46.             } 
  47.         } 
  48.     } 

MapperProxyFactory对象里保存了mapper接口的class对象,就是一个普通的类,没有什么逻辑。

在MapperProxyFactory类中使用了两种设计模式:

  1. 单例模式methodCache(注册式单例模式)。
  2. 工厂模式getMapper()。

继续看MapperProxyFactory中的newInstance方法。

  1. public class MapperProxyFactory<T> { 
  2.       private final Class<T> mapperInterface; 
  3.       private final Map<Method, MapperMethod> methodCache = new ConcurrentHashMap<>(); 
  4.      
  5.       public MapperProxyFactory(Class<T> mapperInterface) { 
  6.         this.mapperInterface = mapperInterface; 
  7.       } 
  8.      public T newInstance(SqlSession sqlSession) { 
  9.       //创建MapperProxy对象 
  10.       final MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession, mapperInterface, methodCache); 
  11.       return newInstance(mapperProxy); 
  12.     } 
  13.     //最终以JDK动态代理创建对象并返回 
  14.      protected T newInstance(MapperProxy<T> mapperProxy) { 
  15.         return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy); 
  16.     } 
  17.     } 

从代码中可以看出,依然是稳稳的基于 JDK Proxy 实现的,而 InvocationHandler 参数是 MapperProxy 对象。

  1. //UserMapper 的类加载器 
  2. //接口是UserMapper 
  3. //h是mapperProxy对象 
  4. public static Object newProxyInstance(ClassLoader loader, 
  5.                                           Class<?>[] interfaces, 
  6.                                        InvocationHandler h){ 

问题2:为什么就可以调用他的方法?

上面调用newInstance方法时候创建了MapperProxy对象,并且是当做newProxyInstance的第三个参数,所以MapperProxy类肯定实现了InvocationHandler。

进入MapperProxy类中:

  1. //果然实现了InvocationHandler接口 
  2.   public class MapperProxy<T> implements InvocationHandler, Serializable { 
  3.    
  4.     private static final long serialVersionUID = -6424540398559729838L; 
  5.     private final SqlSession sqlSession; 
  6.     private final Class<T> mapperInterface; 
  7.     private final Map<Method, MapperMethod> methodCache; 
  8.    
  9.     public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> methodCache) { 
  10.       this.sqlSession = sqlSession; 
  11.       this.mapperInterface = mapperInterface; 
  12.       this.methodCache = methodCache; 
  13.     } 
  14.     //调用userMapper.selectById()实质上是调用这个invoke方法 
  15.     @Override 
  16.     public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 
  17.       try { 
  18.         //如果是Object的方法toString()、hashCode()等方法   
  19.         if (Object.class.equals(method.getDeclaringClass())) { 
  20.           return method.invoke(this, args); 
  21.         } else if (method.isDefault()) { 
  22.           //JDK8以后的接口默认实现方法   
  23.           return invokeDefaultMethod(proxy, method, args); 
  24.         } 
  25.       } catch (Throwable t) { 
  26.         throw ExceptionUtil.unwrapThrowable(t); 
  27.       } 
  28.       //创建MapperMethod对象 
  29.       final MapperMethod mapperMethod = cachedMapperMethod(method); 
  30.       //下一篇再聊 
  31.       return mapperMethod.execute(sqlSession, args); 
  32.     } 
  33.   } 

也就是说,getMapper方法返回的是一个JDK动态代理对象(类型是$Proxy+数字)。这个代理对象会继承Proxy类,实现被代理的接口UserMpper,里面持有了一个MapperProxy类型的触发管理类。

当我们调用UserMpper的方法时候,实质上调用的是MapperProxy的invoke方法。

  1. userMapper=$Proxy6@2355。 

为什么要在MapperRegistry中保存一个工厂类?

原来他是用来创建并返回代理类的。这里是代理模式的一个非常经典的应用。

MapperProxy如何实现对接口的代理?

JDK动态代理

我们知道,JDK动态代理有三个核心角色:

  • 被代理类(即就是实现类)
  • 接口
  • 实现了InvocationHanndler的触发管理类,用来生成代理对象。

被代理类必须实现接口,因为要通过接口获取方法,而且代理类也要实现这个接口。

而Mybatis中并没有Mapper接口的实现类,怎么被代理呢?它忽略了实现类,直接对Mapper接口进行代理。

MyBatis动态代理:

在Mybatis中,JDK动态代理为什么不需要实现类呢?

这里我们的目的其实就是根据一个可以执行的方法,直接找到Mapper.xml中statement ID ,方便调用。

最后返回的userMapper就是MapperProxyFactory的创建的代理对象,然后这个对象中包含了MapperProxy对象,

问题3:到底是怎么根据Mapper.java找到Mapper.xml的?

最后我们调用userMapper.selectUserById(),本质上调用的是MapperProxy的invoke()方法。

请看下面这张图:

如果根据(接口+方法名找到Statement ID ),这个逻辑在InvocationHandler子类(MapperProxy类)中就可以完成了,其实也就没有必要在用实现类了。

总结

本文中主要是讲getMapper方法,该方法实质上是获取一个JDK动态代理对象(类型是Proxy+数字),这个代理类会继承MapperProxy类,实现被代理的接口UserMapper,并且里面持有一个MapperProxy类型的触发管理类。这里我们就拿到代理类了,后面我们就可以使用这个代理对象进行方法调用。

问题涉及到的设计模式:

  1. 代理模式。
  2. 工厂模式。
  3. 单例模式。

整个流程图:

本文转载自微信公众号「Java后端技术全栈」,可以通过以下二维码关注。转载本文请联系Java后端技术全栈公众号。

 

责任编辑:武晓燕 来源: Java后端技术全栈
相关推荐

2020-03-23 12:58:34

美团公有云互联网

2018-04-23 09:50:54

2023-03-28 21:33:53

面试隔离MVCC

2023-05-22 08:17:04

2023-12-20 07:36:58

GoLinux语言

2022-09-05 15:36:47

线程方法Java

2022-02-15 07:03:04

start 源码run线程

2023-11-30 08:16:19

SpringjarTomcat

2023-05-09 10:05:24

HashMapNull

2022-06-15 09:02:32

JVM线程openJDK

2023-09-29 11:50:10

接口编程代码

2013-08-20 13:11:58

技术美团

2022-03-03 16:45:02

美团述职反馈

2017-06-01 10:52:35

互联网

2021-08-29 18:36:17

MySQL技术面试题

2016-11-27 20:43:26

云计算迭代

2023-07-05 08:17:38

JDK动态代理接口

2022-01-04 06:56:43

面试Java方法重载

2020-07-15 09:29:23

Python开发工具

2023-01-31 08:44:50

SQL语句查询
点赞
收藏

51CTO技术栈公众号