MyBatis的擴充套件點(plugins)
阿新 • • 發佈:2018-11-29
1、解析mybatis.xml配置檔案中的plugins標籤,將Interceptor屬性定義的Interceptor放到interceptorChain中;
// SqlSession的建立過程,SqlSessionFactoryBuilder建立DefaultSqlSessionFactory(建立DefaultSqlSession)
SqlSession sqlSession = new SqlSessionFactoryBuilder().build(in, "development", pro).openSession();
// SqlSessionFactoryBuilder.java public SqlSessionFactory build(Reader reader, String environment, Properties properties) { try { XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties); // 解析mybatis.xml配置檔案,並建立DefaultSqlSessionFactory return build(parser.parse()); } catch (Exception e) { throw ExceptionFactory.wrapException("Error building SqlSession.", e); } finally { ErrorContext.instance().reset(); try { reader.close(); } catch (IOException e) { // Intentionally ignore. Prefer previous error. } } }
// XMLConfigBuilder.java public Configuration parse() { if (parsed) { throw new BuilderException("Each XMLConfigBuilder can only be used once."); } parsed = true; parseConfiguration(parser.evalNode("/configuration")); return configuration; } // 解析mybatis.xml中的各個標籤 private void parseConfiguration(XNode root) { try { propertiesElement(root.evalNode("properties")); //issue #117 read properties first typeAliasesElement(root.evalNode("typeAliases")); pluginElement(root.evalNode("plugins")); objectFactoryElement(root.evalNode("objectFactory")); objectWrapperFactoryElement(root.evalNode("objectWrapperFactory")); settingsElement(root.evalNode("settings")); environmentsElement(root.evalNode("environments")); // read it after objectFactory and objectWrapperFactory issue #631 databaseIdProviderElement(root.evalNode("databaseIdProvider")); typeHandlerElement(root.evalNode("typeHandlers")); mapperElement(root.evalNode("mappers")); } catch (Exception e) { throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e); } } // 解析plugins標籤,並把Interceptor放到interceptorChain中 private void pluginElement(XNode parent) throws Exception { if (parent != null) { for (XNode child : parent.getChildren()) { String interceptor = child.getStringAttribute("interceptor"); Properties properties = child.getChildrenAsProperties(); Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).newInstance(); interceptorInstance.setProperties(properties); configuration.addInterceptor(interceptorInstance); } } } // Configuration,mybatis檔案的抽象類 public void addInterceptor(Interceptor interceptor) { interceptorChain.addInterceptor(interceptor); }