Mybatis源码分析别名实现机制。

在Mybatis中我们经常会用到将某个bean作为参数类型parameterType或者结果返回值类型ResultType,所以很多时候我们需要把完成的Bean的包名在mapper文件中

  


Mybatis给我们提供了一种叫别名的机制,意思就是对某个具体的类设置别名,在mybatis的配置文件中配置如下:







......




这样之后mapper文件中的select可以写成如下格式:

  



Mybatis相关的解析源码:

//类别名解析
private void typeAliasesElement(XNode parent) {
if (parent != null) {
for (XNode child : parent.getChildren()) {
//如果子节点是package,那么就获取package节点的name属性
if ("package".equals(child.getName())) {
String typeAliasPackage = child.getStringAttribute("name");
configuration.getTypeAliasRegistry().registerAliases(typeAliasPackage);
} else {
//如果子节点是typeAlias节点,那么就获取alias属性和type的属性
String alias = child.getStringAttribute("alias");
String type = child.getStringAttribute("type");
try {
//通过type的值来加载获得类
Class clazz = Resources.classForName(type);
if (alias == null) {
//typeAliasRegistry会进行别名注册
typeAliasRegistry.registerAlias(clazz);
} else {
typeAliasRegistry.registerAlias(alias, clazz);
}
} catch (ClassNotFoundException e) {
throw new BuilderException("Error registering typeAlias for '" + alias + "'. Cause: " + e, e);
}
}
}
}


解析alias来获得别名,解析type元素来获得类名,通过Resources.classForName(type)获得类信息,然后通过typeAliasRegistry.registerAlias(alias, clazz)将类别名注册到typeAliasRegistry中,这样就完成了mybatis中配置文件的解析。


TypeAliasRegistry类源码分析
TypeAliasRegistry:是用来记录别名alias和类clazz之间的对应关系的,它可以看做是一个Map,
alias作为key,类名作为value,详看源码如下:

public class TypeAliasRegistry {

private final Map> TYPE_ALIASES = new HashMap>();

public TypeAliasRegistry() {
registerAlias("string", String.class);

registerAlias("byte", Byte.class);
registerAlias("long", Long.class);
registerAlias("short", Short.class);
registerAlias("int", Integer.class);
registerAlias("integer", Integer.class);
registerAlias("double", Double.class);
registerAlias("float", Float.class);
registerAlias("boolean", Boolean.class);

registerAlias("byte[]", Byte[].class);
registerAlias("long[]", Long[].class);
registerAlias("short[]", Short[].class);
registerAlias("int[]", Integer[].class);
registerAlias("integer[]", Integer[].class);
registerAlias("double[]", Double[].class);
registerAlias("float[]", Float[].class);
registerAlias("boolean[]", Boolean[].class);

registerAlias("_byte", byte.class);
registerAlias("_long", long.class);
registerAlias("_short", short.class);
registerAlias("_int", int.class);
registerAlias("_integer", int.class);
registerAlias("_double", double.class);
registerAlias("_float", float.class);
registerAlias("_boolean", boolean.class);

registerAlias("_byte[]", byte[].class);
registerAlias("_long[]", long[].class);
registerAlias("_short[]", short[].class);
registerAlias("_int[]", int[].class);
registerAlias("_integer[]", int[].class);
registerAlias("_double[]", double[].class);
registerAlias("_float[]", float[].class);
registerAlias("_boolean[]", boolean[].class);

registerAlias("date", Date.class);
registerAlias("decimal", BigDecimal.class);
registerAlias("bigdecimal", BigDecimal.class);
registerAlias("biginteger", BigInteger.class);
registerAlias("object", Object.class);

registerAlias("date[]", Date[].class);
registerAlias("decimal[]", BigDecimal[].class);
registerAlias("bigdecimal[]", BigDecimal[].class);
registerAlias("biginteger[]", BigInteger[].class);
registerAlias("object[]", Object[].class);

registerAlias("map", Map.class);
registerAlias("hashmap", HashMap.class);
registerAlias("list", List.class);
registerAlias("arraylist", ArrayList.class);
registerAlias("collection", Collection.class);
registerAlias("iterator", Iterator.class);

registerAlias("ResultSet", ResultSet.class);
}

@SuppressWarnings("unchecked")
// throws class cast exception as well if types cannot be assigned
public Class resolveAlias(String string) {
try {
if (string == null) {
return null;
}
// issue #748
String key = string.toLowerCase(Locale.ENGLISH);
Class value;
if (TYPE_ALIASES.containsKey(key)) {
value = (Class) TYPE_ALIASES.get(key);
} else {
value = (Class) Resources.classForName(string);
}
return value;
} catch (ClassNotFoundException e) {
throw new TypeException("Could not resolve type alias '" + string + "'. Cause: " + e, e);
}
}



public void registerAliases(String packageName){
registerAliases(packageName, Object.class);
}


public void registerAliases(String packageName, Class superType){
ResolverUtil> resolverUtil = new ResolverUtil>();
resolverUtil.find(new ResolverUtil.IsA(superType), packageName);
Set>> typeSet = resolverUtil.getClasses();
for(Class type : typeSet){
// Ignore inner classes and interfaces (including package-info.java)
// Skip also inner classes. See issue #6
if (!type.isAnonymousClass() && !type.isInterface() && !type.isMemberClass()) {
registerAlias(type);
}
}
}

public void registerAlias(Class type) {
String alias = type.getSimpleName();
Alias aliasAnnotation = type.getAnnotation(Alias.class);
if (aliasAnnotation != null) {
alias = aliasAnnotation.value();
}
registerAlias(alias, type);
}

public void registerAlias(String alias, Class value) {
if (alias == null) {
throw new TypeException("The parameter alias cannot be null");
}
// issue #748
String key = alias.toLowerCase(Locale.ENGLISH);
if (TYPE_ALIASES.containsKey(key) && TYPE_ALIASES.get(key) != null && !TYPE_ALIASES.get(key).equals(value)) {
throw new TypeException("The alias '" + alias + "' is already mapped to the value '" + TYPE_ALIASES.get(key).getName() + "'.");
}
TYPE_ALIASES.put(key, value);
}

public void registerAlias(String alias, String value) {
try {
registerAlias(alias, Resources.classForName(value));
} catch (ClassNotFoundException e) {
throw new TypeException("Error registering type alias "+alias+" for "+value+". Cause: " + e, e);
}
}

/**
* @since 3.2.2
*/
public Map> getTypeAliases() {
return Collections.unmodifiableMap(TYPE_ALIASES);
}

}



解析mybatis的配置文件,将alias元素的值作为Map的key,通过反射机制获得的type元素对应的类名的类作为Map的value值,在真正使用时通过alias别名来获取真正的类。

但是如果配置package情况要复杂的多,下面看下配置package的处理过程。


public void registerAliases(String packageName){
registerAliases(packageName, Object.class);
}

public void registerAliases(String packageName, Class superType){
ResolverUtil> resolverUtil = new ResolverUtil>();


resolverUtil.find(new ResolverUtil.IsA(superType), packageName);

Set>> typeSet = resolverUtil.getClasses();
for(Class type : typeSet){
// Ignore inner classes and interfaces (including package-info.java)
// Skip also inner classes. See issue #6
if (!type.isAnonymousClass() && !type.isInterface() && !type.isMemberClass()) {
registerAlias(type);
}
}
}


我们继续分析ResolverUtil.java的方法,这里IsA是个闭包,里面主要实现一个类视为为parent的子类。 find函数会遍历这个package下面所有的class,如果是Object的子类并切能被classloader加载
缓存起来, resolverUtil.getClasses()就是返回我们缓存的class。


public static class IsA implements Test {
private Class parent;

/** Constructs an IsA test using the supplied Class as the parent class/interface. */
public IsA(Class parentType) {
this.parent = parentType;
}

@Override
public boolean matches(Class type) {
return type != null && parent.isAssignableFrom(type);
}

@Override
public String toString() {
return "is assignable to " + parent.getSimpleName();
}
}


public ResolverUtil find(Test test, String packageName) {
String path = getPackagePath(packageName);

try {
List children = VFS.getInstance().list(path);
for (String child : children) {
if (child.endsWith(".class")) {
addIfMatching(test, child);
}
}
} catch (IOException ioe) {
log.error("Could not read package: " + packageName, ioe);
}

return this;
}

protected String getPackagePath(String packageName) {
return packageName == null ? null : packageName.replace('.', '/');
}

public List list(String path) throws IOException {
List names = new ArrayList();
for (URL url : getResources(path)) {
names.addAll(list(url, path));
}
return names;
}

protected static List getResources(String path) throws IOException {
return Collections.list(Thread.currentThread().getContextClassLoader().getResources(path));
}



protected void addIfMatching(Test test, String fqn) {
try {
String externalName = fqn.substring(0, fqn.indexOf('.')).replace('/', '.');
ClassLoader loader = getClassLoader();
if (log.isDebugEnabled()) {
log.debug("Checking to see if class " + externalName + " matches criteria [" + test + "]");
}

Class type = loader.loadClass(externalName);
if (test.matches(type)) {
matches.add((Class) type);
}
} catch (Throwable t) {
log.warn("Could not examine class '" + fqn + "'" + " due to a " +
t.getClass().getName() + " with message: " + t.getMessage());
}
}

你可能感兴趣的:(Mybatis,java,mybatis源码)