mybatis源碼分析-基礎支持層

XPathParser

mybatis提供給的類對原來的一些類進行了封裝

  • XPathParser中各個字段的含義和功能

      public class XPathParser {
      	private Document document;				//Document對象
       	private boolean validation;				//是否開啓驗證
        	private EntityResolver entityResolver;	//用於加載本地的DTD文件
        	private Properties variables;			//mybatis-config.xml中<propteries>標籤定義的鍵值對集合
        	private XPath xpath;					//XPath對象
      ...
      //主要使用的構造方法
      /*	inputStream:這個是mybatis-config.xml配置文件流
      *	validation:這個參數是是否開啓驗證
      *	variables:null
      *	entityResolver:這個對象主要是加載DTD的
      	public XPathParser(InputStream inputStream, boolean validation, Properties variables, EntityResolver entityResolver) {
      		//這個其實是一些初始化,主要是初始化驗證和創建XPath對象
      		commonConstructor(validation, variables, entityResolver);
      		//InputSource這個主要是加載之後的mybatis-config.xml文件
      		this.document = createDocument(new InputSource(inputStream));
      	}
      	//這個方法就完成了加載mybatis-config.xml文件最後返回一個document
      	private Document createDocument(InputSource inputSource) {
      	// important: this must only be called AFTER common constructor
      	    try {
      	      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      	      factory.setValidating(validation);
      			//進行設置各種配置信息
      	      factory.setNamespaceAware(false);
      	      factory.setIgnoringComments(true);
      	      factory.setIgnoringElementContentWhitespace(false);
      	      factory.setCoalescing(false);
      	      factory.setExpandEntityReferences(true);
      	
      	      DocumentBuilder builder = factory.newDocumentBuilder();
      	      builder.setEntityResolver(entityResolver);
      	      builder.setErrorHandler(new ErrorHandler() {
      	        @Override
      	        public void error(SAXParseException exception) throws SAXException {
      	          throw exception;
      	        }
      	
      	        @Override
      	        public void fatalError(SAXParseException exception) throws SAXException {
      	          throw exception;
      	        }
      	
      	        @Override
      	        public void warning(SAXParseException exception) throws SAXException {
      	        }
      	      });
      			//這個方法纔是真正的獲取document對象
      	      return builder.parse(inputSource);
      	    } catch (Exception e) {
      	      throw new BuilderException("Error creating document instance.  Cause: " + e, e);
      	    }
      	  }
      	
      }
    
  • XMLMapperEntityResolver implements EntityResolver

    • EntityResolver接口對象用來加載本地的DTD所以XMLMapperEntityResolver實現了這個接口

        public class XMLMapperEntityResolver implements EntityResolver {
        	//指定mybatis-config.xml文件和映射文件對應的DTD的SystemID
        	private static final String IBATIS_CONFIG_SYSTEM = "ibatis-3-config.dtd";
          	private static final String IBATIS_MAPPER_SYSTEM = "ibatis-3-mapper.dtd";
          	private static final String MYBATIS_CONFIG_SYSTEM = "mybatis-3-config.dtd";
          	private static final String MYBATIS_MAPPER_SYSTEM = "mybatis-3-mapper.dtd";
        	//指定mybatis-congfig.xml文件和映射文件對應的DTD具體位置
          	private static final String MYBATIS_CONFIG_DTD = "org/apache/ibatis/builder/xml/mybatis-3-config.dtd";
          	private static final String MYBATIS_MAPPER_DTD = "org/apache/ibatis/builder/xml/mybatis-3-mapper.dtd";
        	//核心方法
        	public InputSource resolveEntity(String publicId, String systemId) throws SAXException {
        		try {
        			if (systemId != null) {
        			//查找systemID指定的DTD,並調用InputSource()方法讀取DTD文檔
        			String lowerCaseSystemId = systemId.toLowerCase(Locale.ENGLISH);
        			if (lowerCaseSystemId.contains(MYBATIS_CONFIG_SYSTEM) || lowerCaseSystemId.contains(IBATIS_CONFIG_SYSTEM)) {
          				return getInputSource(MYBATIS_CONFIG_DTD, publicId, systemId);
        			} else if (lowerCaseSystemId.contains(MYBATIS_MAPPER_SYSTEM) || lowerCaseSystemId.contains(IBATIS_MAPPER_SYSTEM)) {
          				return getInputSource(MYBATIS_MAPPER_DTD, publicId, systemId);
        			}
      			}
      				return null;
        		} catch (Exception e) {
      				throw new SAXException(e.toString());
        		}
        	}
        	...
        }
      

反射工具箱

Reflector

Reflector是mybatis的基礎反射模塊,每一個Reflector對象都對應着一個類,Reflector中緩存了反射操作需要使用的類的元信息。

public class Reflector {

		private static final String[] EMPTY_STRING_ARRAY = new String[0];
		//對應的class類型
		private Class<?> type;
		//可讀屬性的名稱集合,可讀屬性就是存在相應的getter方法的*屬性*,初始化的值爲空數組(不是方法名是屬性名)
		private String[] readablePropertyNames = EMPTY_STRING_ARRAY;
		//可寫屬性的名稱集合,可寫屬性就是存在相應的setter方法的*屬性*,初始化的值爲空數組(不是方法名是屬性名)
		private String[] writeablePropertyNames = EMPTY_STRING_ARRAY;
		//記錄了屬性相應的setter方法,key是屬性名稱,value是Invoker方法,它是對settrt方法對應Method對象的封裝。
	  	private Map<String, Invoker> setMethods = new HashMap<String, Invoker>();
		//記錄了屬性相應的getter方法,key是屬性名稱,value是Invoker方法,它是對gettrt方法對應Method對象的封裝。
	  	private Map<String, Invoker> getMethods = new HashMap<String, Invoker>();
		//記錄屬性相應的setter方法的參數值類型,key是屬性名稱,value是setter方法的參數類型
	  	private Map<String, Class<?>> setTypes = new HashMap<String, Class<?>>();
		//記錄屬性相應的getter方法的參數值類型,key是屬性名稱,value是getter方法的參數類型
	  	private Map<String, Class<?>> getTypes = new HashMap<String, Class<?>>();
		//記錄了默認構造方法
	  	private Constructor<?> defaultConstructor;
		//記錄所有屬性名稱的集合
	  	private Map<String, String> caseInsensitivePropertyMap = new HashMap<String, String>();
		...
		//這個構造方法會解析指定的Class對象
		public Reflector(Class<?> clazz) {
		    type = clazz;
			//查找clazz的默認構造方法(無參構造函數),具體實現是通過反射遍歷所有的構造方法
		    addDefaultConstructor(clazz);
		    addGetMethods(clazz);
		    addSetMethods(clazz);
		    addFields(clazz);
			//根據getter和setter方法集合,初始化可讀可寫屬性的名稱集合
		    readablePropertyNames = getMethods.keySet().toArray(new String[getMethods.keySet().size()]);
		    writeablePropertyNames = setMethods.keySet().toArray(new String[setMethods.keySet().size()]);
			//初始化集合,其中記錄了所有大寫格式的屬性名稱
		    for (String propName : readablePropertyNames) {
		      caseInsensitivePropertyMap.put(propName.toUpperCase(Locale.ENGLISH), propName);
		    }
		    for (String propName : writeablePropertyNames) {
		      caseInsensitivePropertyMap.put(propName.toUpperCase(Locale.ENGLISH), propName);
		    }
		 }//解析getter的方法
		private void addGetMethods(Class<?> cls) {
		    Map<String, List<Method>> conflictingGetters = new HashMap<String, List<Method>>();
			//這裏是關鍵獲取當前類以及父類中定義的所有方法的唯一簽名以及相應的Method對象。
		    Method[] methods = getClassMethods(cls);
		    for (Method method : methods) {
		      String name = method.getName();
		      if (name.startsWith("get") && name.length() > 3) {
		        if (method.getParameterTypes().length == 0) {
				  //主要是返回去除了set和get的屬性名字
		          name = PropertyNamer.methodToProperty(name);
		          addMethodConflict(conflictingGetters, name, method);
		        }
		      } else if (name.startsWith("is") && name.length() > 2) {
		        if (method.getParameterTypes().length == 0) {
		          name = PropertyNamer.methodToProperty(name);
		          addMethodConflict(conflictingGetters, name, method);
		        }
		      }
		    }
			//這個方法主要是爲解決覆寫方法的情況進行處理
		    resolveGetterConflicts(conflictingGetters);
		}
		
		private Method[] getClassMethods(Class<?> cls) {
			//用來記錄指定類中定義的全部方法的唯一簽名以及相應的Method對象
		    Map<String, Method> uniqueMethods = new HashMap<String, Method>();
		    Class<?> currentClass = cls;
		    while (currentClass != null) {
			  //記錄這個類中的當前方法
		      addUniqueMethods(uniqueMethods, currentClass.getDeclaredMethods());
		
		      // we also need to look for interface methods -
		      // because the class may be abstract
			  //記錄接口中定義的方法
		      Class<?>[] interfaces = currentClass.getInterfaces();
		      for (Class<?> anInterface : interfaces) {
		        addUniqueMethods(uniqueMethods, anInterface.getMethods());
		      }
			  //獲取父類,繼續while循環
		      currentClass = currentClass.getSuperclass();
		    }
			//得到所有的方法並放到這個集合中
		    Collection<Method> methods = uniqueMethods.values();
			//轉換成method數組返回
		    return methods.toArray(new Method[methods.size()]);
		}
		//這個方法會爲每一個方法生成一個唯一的方法簽名,並記錄到集合中
	  private void addUniqueMethods(Map<String, Method> uniqueMethods, Method[] methods) {
	    for (Method currentMethod : methods) {
	      if (!currentMethod.isBridge()) {
			//通過getSignature方法獲取的方法簽名是:返回值類型#方法名稱:參數類型列表。
	        String signature = getSignature(currentMethod);
	        // check to see if the method is already known
	        // if it is known, then an extended class must have
	        // overridden a method
			//檢查是否在子類中已經添加過該方法,如果在子類中已經添加過,則表示子類覆蓋了該方法,不需要再添加了
	        if (!uniqueMethods.containsKey(signature)) {
			  //是否可以訪問私有的方法
	          if (canAccessPrivateMethods()) {
	            try {
	              currentMethod.setAccessible(true);
	            } catch (Exception e) {
	              // Ignored. This is only a final precaution, nothing we can do.
	            }
	          }
			  //放到集合中
	          uniqueMethods.put(signature, currentMethod);
	        }
	      }
	    }
	  }
	private void resolveGetterConflicts(Map<String, List<Method>> conflictingGetters) {
		for (String propName : conflictingGetters.keySet()) {
  			List<Method> getters = conflictingGetters.get(propName);
  				Iterator<Method> iterator = getters.iterator();
  				Method firstMethod = iterator.next();
  				if (getters.size() == 1) {
    				addGetMethod(propName, firstMethod);
  				} else {
    				Method getter = firstMethod;
    				Class<?> getterType = firstMethod.getReturnType();
    				while (iterator.hasNext()) {
      				Method method = iterator.next();
      				Class<?> methodType = method.getReturnType();
      				if (methodType.equals(getterType)) {
        			throw new ReflectionException("Illegal overloaded getter method with ambiguous type for property "
            		+ propName + " in class " + firstMethod.getDeclaringClass()
            		+ ".  This breaks the JavaBeans " + "specification and can cause unpredicatble results.");
      			} else if (methodType.isAssignableFrom(getterType)) {
        		// OK getter type is descendant
      			} else if (getterType.isAssignableFrom(methodType)) {
        			getter = method;
        			getterType = methodType;
      			} else {
        			throw new ReflectionException("Illegal overloaded getter method with ambiguous type for property "
            		+ propName + " in class " + firstMethod.getDeclaringClass()
            		+ ".  This breaks the JavaBeans " + "specification and can cause unpredicatble results.");
      			}
    		}
    		addGetMethod(propName, getter);
  			}
		}
	}
	......
}## Invoker ##

所有的對象都會封裝成這個類型

public interface Invoker {
	//調用獲取指定字段的值或執行指定的方法
	Object invoke(Object target, Object[] args) throws IllegalAccessException, InvocationTargetException;
	//返回屬性相應的類型
	Class<?> getType();
}

Invoker接口實現

public interface Invoker {
  Object invoke(Object target, Object[] args) throws IllegalAccessException, InvocationTargetException;

  Class<?> getType();
}

ReflectorFactory

主要是用來創建Reflector
public interface ReflectorFactory {

  boolean isClassCacheEnabled();

  void setClassCacheEnabled(boolean classCacheEnabled);

  Reflector findForClass(Class<?> type);
}

mybatis只爲這個接口提供了DefaultReflectorFactor這一實現類,關係圖如下:

DefaultReflectorFactory

public class DefaultReflectorFactory implements ReflectorFactory {
	private boolean classCacheEnabled = true;//該字段決定是否對Reflector對象的緩存
	//使用ConcurrentMap集合實現對Reflector對象的緩存
	private final ConcurrentMap<Class<?>, Reflector> reflectorMap = new ConcurrentHashMap<Class<?>, Reflector>();

	public DefaultReflectorFactory() {
	}

	@Override
	public boolean isClassCacheEnabled() {
		return classCacheEnabled;
	}

	@Override
	public void setClassCacheEnabled(boolean classCacheEnabled) {
		this.classCacheEnabled = classCacheEnabled;
	}

	//爲指定的Class創建Reflector對象,並將Reflector對象緩存到reflectorMap中
	@Override
	public Reflector findForClass(Class<?> type) {
		if (classCacheEnabled) {
			// synchronized (type) removed see issue #461
			Reflector cached = reflectorMap.get(type);
			if (cached == null) {
				cached = new Reflector(type);
				reflectorMap.put(type, cached);
			}
			return cached;
		} else {
			return new Reflector(type);//未開啓則直接創建
		}
	}

}

TypeParameterResolver

先介紹一下Type接口,它一共有四個子接口和一個實現類,類圖關係如下;

Class:它表示原始類型。Class類對象表示JVM中的一個類或者接口,每個java類在JVM裏都表示爲一個Class對象。在程序中通過“類名.class”,對象.getClass()或是Class.forName(“類名”)等方式獲取Class對象。數組也被映射爲Class對象

ParameterizedType表示的是參數化類型,例如List、Map<Integer,String>等這種帶着泛型的類型

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章