publicclassMapperRegistry{//配置对象privatefinal Configuration config;//接口与代理工厂的映射关系privatefinal Map<Class<?>, MapperProxyFactory<?>> knownMappers =newHashMap<Class<?>, MapperProxyFactory<?>>();//获取代理对象过程public<T> T getMapper(Class<T> type, SqlSession sqlSession){//根据接口类型,获取该接口的代理工厂final MapperProxyFactory<T> mapperProxyFactory =(MapperProxyFactory<T>) knownMappers.get(type);//没有时,抛出异常if(mapperProxyFactory == null){thrownewBindingException("Type "+ type +" is not known to the MapperRegistry.");}try{//代理工厂创建一个代理对象实例return mapperProxyFactory.newInstance(sqlSession);}catch(Exception e){thrownewBindingException("Error getting mapper instance. Cause: "+ e, e);}}
5 进入工厂类中,查看生产代理实例的过程
类 : MapperProxyFactory
方法 : newInstance()
作用 : 代理工厂类,生产代理实例 MapperProxy对象 的过程
public T newInstance(SqlSession sqlSession){//MapperProxy对象实现了invocationHandler接口,该类为所有接口的代理类final MapperProxy<T> mapperProxy =newMapperProxy<T>(sqlSession, mapperInterface, methodCache);returnnewInstance(mapperProxy);}
protected T newInstance(MapperProxy<T> mapperProxy){//生产代理实例API (被代理类加载器,被代理类的接口,实现invocationHandler接口类)return(T) Proxy.newProxyInstance(mapperInterface.getClassLoader(),newClass[]{ mapperInterface }, mapperProxy);}