在上一篇文章中,我们梳理了阅读Mybatis源码的全过程。今天就来详细说说Mybatis是如何解析配置文件的。这是今天分析的流程图:还是从案例说起。演示案例)sqlSession=sqlSessionFactory.openSession();UserMapperuserMapper=sqlSession.getMapper(UserMapper.class);System.out.println(userMapper.selectById(1));}catch(Exceptione){e.printStackTrace();}最后{try{inputStream.close();}catch(IOExceptione){e.printStackTrace();}sqlSession.close();}}见证SqlSessionFactoryBuilder的奇迹。SqlSessionFactoryBuilder类org.apache.ibatis.session.SqlSessionFactoryBuilder充满了构建方法的各种重载。//这个方法什么都没做,environment,properties);returnbuild(parser.parse());}catch(Exceptione){throwExceptionFactory.wrapException("ErrorbuildingSqlSession.",e);}finally{ErrorContext.instance().reset();try{inputStream.close();}catch(IOExceptione){//Intentionallyignore.Preferpreviouserror.}}}XMLConfigBuilder类重载了该类的构造方法:首先进入:publicXMLConfigBuilder(InputStreaminputStream,Stringenvironment,Propertiesprops){this(newXPathParser(inputStream,true,props,newXMLMapperEntityResolver()),environment,props);}privateXMLConfigBuilder(XPathParserparser,Stringenvironment,Propertiesprops){super(newConfiguration());ErrorContext.instance().resource("SQLMapperConfiguration");this.configuration.setVariables(props);this.parsed=false;this.environment=environment;this.parser=parser;}build(parser.parse());mybatis-config.xml中的parser.parse()在哪里解析呢?请看下面的方法://该方法返回一个Configuration对象publicConfigurationparse(){if(parsed){thrownewBuilderException("EachXMLConfigBuildercanonlybeusedonce.");}parsed=true;//关键点parseConfiguration(parser.evalNode("/configuration"));returnconfiguration;}parseConfiguration(parser.evalNode("/configuration"));终于看到开始解析配置文件了:进入方法parseConfigurationprivatevoidparseConfiguration(XNoderoot){try{//issue#117readpropertiesfirstpropertiesElement(root.evalNode("properties"));Propertiessettings=settingsAsProperties(root.evalNode("settings"));loadCustomVfs(settings);loadCustomLogImpl(settings);typeAliasesElement(root).evalNode("typeAliases"));pluginElement(root.evalNode("plugins"));objectFactoryElement(root.evalNode("objectFactory"));objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));reflectorFactoryElement(root.evalNode("reflectorFactory"));settingsElement(settings);//在objectFactoryandobjectWrapperFactoryissue#631environmentsElement(root.evalNode("environments"));databaseIdProviderElement(root.evalNode("databaseIdProvider"));typeHandlerElement(root.evalNode("typeHandlers")));mapperElement(root.evalNode("mappers"));}catch(Exceptione){thrownewBuilderException("ErrorparsingSQLMapperConfiguration.Cause:"+e,e);}}这里是解析mybatis-config.xml的内容,然后设置到Configuration对象中那么我们定义的Mapper.xml是在哪里解析的呢?我们的Mapper.xml在mybatis-config.xml中的配置如下:有四种使用方式://1使用类路径
