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>等这种带着泛型的类型