mybatis核心组件之MapperAnnotationBuilder
缘起: 上章详细讲解了
Mapper
映射接口注册过程的源码
mybatis与spring的整合以及源码分析,本章继续分析解析
Mapper
映射接口。
继上章
// 注册映射接口
this.knownMappers.put(type, new MapperProxyFactory(type));
// 解析映射接口
MapperAnnotationBuilder parser = new MapperAnnotationBuilder(this.config, type);
parser.parse();
MapperAnnotationBuilder构造函数
public MapperAnnotationBuilder(Configuration configuration, Class<?> type) {
String resource = type.getName().replace('.', '/') + ".java (best guess)";
// 处理缓存
this.assistant = new MapperBuilderAssistant(configuration, resource);
this.configuration = configuration;
this.type = type;
// 添加注解类型
this.sqlAnnotationTypes.add(Select.class);
this.sqlAnnotationTypes.add(Insert.class);
this.sqlAnnotationTypes.add(Update.class);
this.sqlAnnotationTypes.add(Delete.class);
this.sqlProviderAnnotationTypes.add(SelectProvider.class);
this.sqlProviderAnnotationTypes.add(InsertProvider.class);
this.sqlProviderAnnotationTypes.add(UpdateProvider.class);
this.sqlProviderAnnotationTypes.add(DeleteProvider.class);
}
parse解析xml与注解
解析配置文件是在MapperAnnotationBuilder类的parse
方法里完成的,该方法先解析配置文件,然后再解析接口里的注解配置,且注解里的配置会覆盖配置文件里的配置,也就是说注解的优先级高于配置文件,这点需要注意。采用自动扫描会大大简化配置,只不过需要应用程序自己调用,mybatis
默认是不会调用这个方法的,mybatis与spring
的整合的自动扫描
就调用到了这个方法。
public void parse() {
String resource = this.type.toString();
// 判断是否已经加载过资源
if (!this.configuration.isResourceLoaded(resource)) {
// 先加载xml资源
this.loadXmlResource();
// 添加解析过的映射,下次判断有就不在解析
this.configuration.addLoadedResource(resource);
// 命名空间
this.assistant.setCurrentNamespace(this.type.getName());
// 二级缓存的处理
this.parseCache();
this.parseCacheRef();
// 方法
Method[] methods = this.type.getMethods();
Method[] arr$ = methods;
int len$ = methods.length;
for(int i$ = 0; i$ < len$; ++i$) {
Method method = arr$[i$];
try {
if (!method.isBridge()) {
// 解析方法
this.parseStatement(method);
}
} catch (IncompleteElementException var8) {
this.configuration.addIncompleteMethod(new MethodResolver(this, method));
}
}
}
this.parsePendingMethods();
}
loadXmlResource()解析映射接口对应的xml文件
<