public <T> voidaddMapper(Class<T> type) { // 接口 if (type.isInterface()) { // 未添加过 if (hasMapper(type)) { thrownewBindingException("Type " + type + " is already known to the MapperRegistry."); } booleanloadCompleted=false; try { // 添加到 knownMappers 中 knownMappers.put(type, newMapperProxyFactory<>(type)); // It's important that the type is added before the parser is run // otherwise the binding may automatically be attempted by the // mapper parser. If the type is already known, it won't try. // 解析 Mapper 的注解位置 MapperAnnotationBuilderparser=newMapperAnnotationBuilder(config, type); parser.parse(); // 加载完成 loadCompleted = true; } finally { // 未加载完成 移除 if (!loadCompleted) { knownMappers.remove(type); } } } }
1.5 getMapper
1 2 3 4 5 6 7 8 9 10 11
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); } }
public T newInstance(SqlSession sqlSession) { final MapperProxy<T> mapperProxy = newMapperProxy<>(sqlSession, mapperInterface, methodCache); return newInstance(mapperProxy); }