mybatis源码解析之Configuration加载(五)

时间:2022-08-13 14:52:17

概述

前面几篇文章主要看了mybatis配置文件configuation.xml中<setting>,<environments>标签的加载,接下来看一下mapper标签的解析,先来看下标签的配置:

     <mappers>
<!-- 方式一,mapper类和xml文件可以不再同一个目录下 -->
<!-- <mapper resource="mapper/newsMapper.xml" /> --> <!-- 方式二,必须保证mapper类和xml文件在同一个目录下 -->
<!--<package name="com.mybatis.read.dao" /> --> <!-- 方式三,必须保证mapper类和xml文件在同一个目录下 -->
<mapper class="com.mybatis.read.dao.NewsMapper" />
</mappers>

常用的主要就有上面三种方式,指定mapper的xml文件,指定package,指定mapper文件,我们来具体解析下。

解析

我们看下具体开始解析的代码:

   private void mapperElement(XNode parent) throws Exception {
if (parent != null) {
for (XNode child : parent.getChildren()) {
if ("package".equals(child.getName())) {
String mapperPackage = child.getStringAttribute("name");
configuration.addMappers(mapperPackage);
} else {
String resource = child.getStringAttribute("resource");
String url = child.getStringAttribute("url");
String mapperClass = child.getStringAttribute("class");
if (resource != null && url == null && mapperClass == null) {
ErrorContext.instance().resource(resource);
InputStream inputStream = Resources.getResourceAsStream(resource);
XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
mapperParser.parse();
} else if (resource == null && url != null && mapperClass == null) {
ErrorContext.instance().resource(url);
InputStream inputStream = Resources.getUrlAsStream(url);
XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments());
mapperParser.parse();
} else if (resource == null && url == null && mapperClass != null) {
Class<?> mapperInterface = Resources.classForName(mapperClass);
configuration.addMapper(mapperInterface);
} else {
throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");
}
}
}
}
}

这段代码就是针对上面不同的配置进行解析加载,这里面还有一种url的情况,是通过url加载外部的资源,不常用。

我们先来看配置了package的情形,

第5行代码,获取包名,第6行代码调用configuration的addMappers方法,具体看下:

   public void addMappers(String packageName) {
mapperRegistry.addMappers(packageName);
}

configuation中又调用了mapperRegistry的addMappers方法:

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

在看下addMappers方法:

   public void addMappers(String packageName, Class<?> superType) {
ResolverUtil<Class<?>> resolverUtil = new ResolverUtil<Class<?>>();
resolverUtil.find(new ResolverUtil.IsA(superType), packageName);
Set<Class<? extends Class<?>>> mapperSet = resolverUtil.getClasses();
for (Class<?> mapperClass : mapperSet) {
addMapper(mapperClass);
}
}

上面这段代码主要就是利用ResolverUtil遍历package下面的所有class文件,看下find方法:

   public ResolverUtil<T> find(Test test, String packageName) {
String path = getPackagePath(packageName); try {
List<String> 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;
}

很明显,上面就是根据包名获取下面的class,然后调用addIfMatching方法:

   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<T>) type);
}
} catch (Throwable t) {
log.warn("Could not examine class '" + fqn + "'" + " due to a " +
t.getClass().getName() + " with message: " + t.getMessage());
}
}

这个方法主要就是根据前面传过来的class,去加载这个类,注意这边用的类加载器是线程上下文类加载器,然后判断这个类的类型是不是Object类,是的话,就放入matches这个set中,都遍历完成之后,符合要求的class就在这个set中,怎么获取呢?看下getClass方法:

   public Set<Class<? extends T>> getClasses() {
return matches;
}

这边调用getClass方法时就返回了这个Set,我们接着看mapperRegistry的addMappers方法,

   public void addMappers(String packageName, Class<?> superType) {
ResolverUtil<Class<?>> resolverUtil = new ResolverUtil<Class<?>>();
resolverUtil.find(new ResolverUtil.IsA(superType), packageName);
Set<Class<? extends Class<?>>> mapperSet = resolverUtil.getClasses();
for (Class<?> mapperClass : mapperSet) {
addMapper(mapperClass);
}
}

按照上面的分析,第4行代码,我们已经得到的复合条件的class,下面就是遍历这些class,调用addMapper方法:

   public <T> void addMapper(Class<T> type) {
if (type.isInterface()) {
if (hasMapper(type)) {
throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
}
boolean loadCompleted = false;
try {
knownMappers.put(type, new MapperProxyFactory<T>(type));
// It's important that the type is added before the parser is run
// otherwise the binding may automatically be attempted by the
// mapper parser. If the type is already known, it won't try.
MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
parser.parse();
loadCompleted = true;
} finally {
if (!loadCompleted) {
knownMappers.remove(type);
}
}
}
}

这段代码首先判断这个class的类型是不是接口,不是则直接跳过,是的话,判断这个class对应的mapper文件是不是已经加载了,是的话,则抛出异常,否则看下第8行代码,将当前class类作为key,new一个MapperProxyFactory作为value放入knownMappers这个map中,这边这个MapperProxyFactory我们后面会详细介绍,看第12行代码,这边new了一个MapperAnnotationBuilder,看下第13行代码,调用了MapperAnnotationBuilder的parse方法:

   public void parse() {
String resource = type.toString();
if (!configuration.isResourceLoaded(resource)) {
loadXmlResource();
configuration.addLoadedResource(resource);
assistant.setCurrentNamespace(type.getName());
parseCache();
parseCacheRef();
Method[] methods = type.getMethods();
for (Method method : methods) {
try {
// issue #237
if (!method.isBridge()) {
parseStatement(method);
}
} catch (IncompleteElementException e) {
configuration.addIncompleteMethod(new MethodResolver(this, method));
}
}
}
parsePendingMethods();
}

这边我们只要关注第4行代码,第5行代码之后都是针对注解做的处理,具体看下:

   private void loadXmlResource() {
// Spring may not know the real resource name so we check a flag
// to prevent loading again a resource twice
// this flag is set at XMLMapperBuilder#bindMapperForNamespace
if (!configuration.isResourceLoaded("namespace:" + type.getName())) {
String xmlResource = type.getName().replace('.', '/') + ".xml";
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(type.getClassLoader(), xmlResource);
} catch (IOException e) {
// ignore, resource is not required
}
if (inputStream != null) {
XMLMapperBuilder xmlParser = new XMLMapperBuilder(inputStream, assistant.getConfiguration(), xmlResource, configuration.getSqlFragments(), type.getName());
xmlParser.parse();
}
}
}

这边首先再次确认xml文件有没有被加载过,没有的话继续加载,在当前目录下根据mapper的名字寻找xml文件,然后加载成流,之后交给XmlMapperBuilder处理,其实到这边,xml就已经加载完成了,后续都是处理一些使用了注解的东西,使用注解我们暂且不看。

我们再来看下方法三:

mapperClass不为空,走第三个if:

   private void mapperElement(XNode parent) throws Exception {
if (parent != null) {
for (XNode child : parent.getChildren()) {
if ("package".equals(child.getName())) {
String mapperPackage = child.getStringAttribute("name");
configuration.addMappers(mapperPackage);
} else {
String resource = child.getStringAttribute("resource");
String url = child.getStringAttribute("url");
String mapperClass = child.getStringAttribute("class");
if (resource != null && url == null && mapperClass == null) {
ErrorContext.instance().resource(resource);
InputStream inputStream = Resources.getResourceAsStream(resource);
XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
mapperParser.parse();
} else if (resource == null && url != null && mapperClass == null) {
ErrorContext.instance().resource(url);
InputStream inputStream = Resources.getUrlAsStream(url);
XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments());
mapperParser.parse();
} else if (resource == null && url == null && mapperClass != null) {
Class<?> mapperInterface = Resources.classForName(mapperClass);
configuration.addMapper(mapperInterface);
} else {
throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");
}
}
}
}
}

第22行代码,根据名称加载mapper类,然后调用configuation的addMapper方法,这个我们上面已经分析过了,其实这种情况跟用package的很相似,可以说是一种特殊情况,package里面会有很多的mapper。

我们再看下方法一:

resource不为空:

           if (resource != null && url == null && mapperClass == null) {
ErrorContext.instance().resource(resource);
InputStream inputStream = Resources.getResourceAsStream(resource);
XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
mapperParser.parse();
}

这边跟上面那个部分一样的,我们下一篇文章就主要看下这个解析过程。