<typeAliases>
标签读取
typeAliasesElement(XNode parent)
方法解析<typeAliases>
标签,将配置类注册到typeAliasRegistry中
配置文件mybatis-config.xml
如下:
<typeAliases>
<typeAlias alias="BlogAuthor" type="org.apache.ibatis.domain.blog.Author"/>
<typeAlias type="org.apache.ibatis.domain.blog.Blog"/>
<typeAlias type="org.apache.ibatis.domain.blog.Post"/>
<package name="org.apache.ibatis.domain.jpetstore"/>
</typeAliases>
复制代码
代码如下:
// XMLConfigBuilder.java
private void typeAliasesElement(XNode parent) {
if (parent != null) {
// 遍历子节点
for (XNode child : parent.getChildren()) {
// 指定为包的情况下,注册包下的每个类
if ("package".equals(child.getName())) {
String typeAliasPackage = child.getStringAttribute("name");
configuration.getTypeAliasRegistry().registerAliases(typeAliasPackage);
// 指定为类的情况下,直接注册类和别名
} else {
String alias = child.getStringAttribute("alias");
String type = child.getStringAttribute("type");
try {
Class<?> clazz = Resources.classForName(type); // 获得类是否存在
// 注册到 typeAliasRegistry 中
if (alias == null) {
typeAliasRegistry.registerAlias(clazz);
} else {
typeAliasRegistry.registerAlias(alias, clazz);
}
} catch (ClassNotFoundException e) { // 若类不存在,则抛出 BuilderException 异常
throw new BuilderException("Error registering typeAlias for '" + alias + "'. Cause: " + e, e);
}
}
}
}
}
//TypeAliasRegistry.java
public void registerAlias(Class<?> type) {
//1.得到类的简写名称
String alias = type.getSimpleName();
//2.类上是否有@Alias注解 有取定义的属性值
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");
}
// 3.别名小写
String key = alias.toLowerCase(Locale.ENGLISH);
// 4.重复别名,且类不同 报异常
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);
}
复制代码
指定 package 中的 Java Bean,在没有注解的情况下,会使用 Bean 的首字母小写的非限定类名来作为它的别名。 比如 domain.blog.Author 的别名为 author;若有注解,则别名为其注解值。看下面的例子:
@Alias("author")
public class Author {
...
}
复制代码
失控的阿甘,乐于分享,记录点滴