mybatis - mapper.java 的创建

一. Mapper.java 创建过程

在前面注册 bean 的时候, 对beanClass 进行了替换, 为 MapperFactoryBean. 那么创建实例的时候, 会调用 MapperFactoryBean 的 getObject() 方法得到实例. 

  @Override
  public T getObject() throws Exception {
    return getSqlSession().getMapper(this.mapperInterface);
  }

  public SqlSession getSqlSession() {
    return this.sqlSession;
  }

这里的的 sqlSession 就是 前面在配置类中创建的 SqlSessionTemplate 实例.

所以 getMapper 调用的就是 SqlSessionTemplate 的 getMapper 方法. 具体调用过程有点曲折, 最后会调用  MapperRegistry 的 getMapper 方法

  // SqlSessionTemplate.java
  @Override
  public  T getMapper(Class type) {
    return getConfiguration().getMapper(type, this);
  }

 |
 |
\|/
 
// Configuration.java public T getMapper(Class type, SqlSession sqlSession) { return mapperRegistry.getMapper(type, sqlSession); } | | \|/
// MapperRegistry.java public T getMapper(Class type, SqlSession sqlSession) { final MapperProxyFactory mapperProxyFactory = (MapperProxyFactory) knownMappers.get(type); if (mapperProxyFactory == null) { throw new BindingException("Type " + type + " is not known to the MapperRegistry."); } try { return mapperProxyFactory.newInstance(sqlSession); } catch (Exception e) { throw new BindingException("Error getting mapper instance. Cause: " + e, e); } }

newInstance 调用的是  MapperProxyFactory 的方法:

  //MapperProxyFactory.java
public T newInstance(SqlSession sqlSession) { final MapperProxy mapperProxy = new MapperProxy(sqlSession, mapperInterface, methodCache); return newInstance(mapperProxy); } protected T newInstance(MapperProxy mapperProxy) { return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy); }

从这里可以看到, 对于 UserMapper.java 接口, 采用了 jdk代理 的方式来创建一个实例. 且代理处理类为:  MapperProxy

 

 

 

你可能感兴趣的:(mybatis - mapper.java 的创建)