上次给你们介绍了一下properties 和 environments 的配置, 接下来就正式开始看源码了:java
上次例子中,咱们以 SqlSessionFactoryBuilder 去建立 SqlSessionFactory, 那么,咱们就先从SqlSessionFactoryBuilder入手, 我们先看看源码是怎么实现的:sql
SqlSessionFactoryBuilder源码片断:mybatis
1app 2ide 3sqlserver 4测试 5ui 6this 7url 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
|
经过源码,咱们能够看到SqlSessionFactoryBuilder 经过XMLConfigBuilder 去解析咱们传入的mybatis的配置文件, 下面就接着看看 XMLConfigBuilder 部分源码:
咱们说过mybatis 是经过XMLConfigBuilder这个类在解析mybatis配置文件的,那么本次就接着看看XMLConfigBuilder对于properties和environments的解析:
XMLConfigBuilder:
1 public class XMLConfigBuilder extends BaseBuilder {23 private boolean parsed;4 //xml解析器5 private XPathParser parser;6 private String environment;78 //上次说到这个方法是在解析mybatis配置文件中能配置的元素节点9 //今天首先要看的就是properties节点和environments节点10 private void parseConfiguration(XNode root) {11 try {12 //解析properties元素13 propertiesElement(root.evalNode("properties")); //issue #117 read properties first14 typeAliasesElement(root.evalNode("typeAliases"));15 pluginElement(root.evalNode("plugins"));16 objectFactoryElement(root.evalNode("objectFactory"));17 objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));18 settingsElement(root.evalNode("settings"));19 //解析environments元素20 environmentsElement(root.evalNode("environments")); // read it after objectFactory and objectWrapperFactory issue #63121 databaseIdProviderElement(root.evalNode("databaseIdProvider"));22 typeHandlerElement(root.evalNode("typeHandlers"));23 mapperElement(root.evalNode("mappers"));24 } catch (Exception e) {25 throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);26 }27 }282930 //下面就看看解析properties的具体方法31 private void propertiesElement(XNode context) throws Exception {32 if (context != null) {33 //将子节点的 name 以及value属性set进properties对象34 //这儿能够注意一下顺序,xml配置优先, 外部指定properties配置其次35 Properties defaults = context.getChildrenAsProperties();36 //获取properties节点上 resource属性的值37 String resource = context.getStringAttribute("resource");38 //获取properties节点上 url属性的值, resource和url不能同时配置39 String url = context.getStringAttribute("url");40 if (resource != null && url != null) {41 throw new BuilderException("The properties element cannot specify both a URL and a resource based property file reference. Please specify one or the other.");42 }43 //把解析出的properties文件set进Properties对象44 if (resource != null) {45 defaults.putAll(Resources.getResourceAsProperties(resource));46 } else if (url != null) {47 defaults.putAll(Resources.getUrlAsProperties(url));48 }49 //将configuration对象中已配置的Properties属性与刚刚解析的融合50 //configuration这个对象会装载所解析mybatis配置文件的全部节点元素,之后也会频频提到这个对象51 //既然configuration对象用有一系列的get/set方法, 那是否就标志着咱们可使用java代码直接配置?52 //答案是确定的, 不过使用配置文件进行配置,优点不言而喻53 Properties vars = configuration.getVariables();54 if (vars != null) {55 defaults.putAll(vars);56 }57 //把装有解析配置propertis对象set进解析器, 由于后面可能会用到58 parser.setVariables(defaults);59 //set进configuration对象60 configuration.setVariables(defaults);61 }62 }6364 //下面再看看解析enviroments元素节点的方法65 private void environmentsElement(XNode context) throws Exception {66 if (context != null) {67 if (environment == null) {68 //解析environments节点的default属性的值69 //例如: <environments default="development">70 environment = context.getStringAttribute("default");71 }72 //递归解析environments子节点73 for (XNode child : context.getChildren()) {74 //<environment id="development">, 只有enviroment节点有id属性,那么这个属性有何做用?75 //environments 节点下能够拥有多个 environment子节点76 //相似于这样: <environments default="development"><environment id="development">...</environment><environment id="test">...</environments>77 //意思就是咱们能够对应多个环境,好比开发环境,测试环境等, 由environments的default属性去选择对应的enviroment78 String id = child.getStringAttribute("id");79 //isSpecial就是根据由environments的default属性去选择对应的enviroment80 if (isSpecifiedEnvironment(id)) {81 //事务, mybatis有两种:JDBC 和 MANAGED, 配置为JDBC则直接使用JDBC的事务,配置为MANAGED则是将事务托管给容器,82 TransactionFactory txFactory = transactionManagerElement(child.evalNode("transactionManager"));83 //enviroment节点下面就是dataSource节点了,解析dataSource节点(下面会贴出解析dataSource的具体方法)84 DataSourceFactory dsFactory = dataSourceElement(child.evalNode("dataSource"));85 DataSource dataSource = dsFactory.getDataSource();86 Environment.Builder environmentBuilder = new Environment.Builder(id)87 .transactionFactory(txFactory)88 .dataSource(dataSource);89 //老规矩,会将dataSource设置进configuration对象90 configuration.setEnvironment(environmentBuilder.build());91 }92 }93 }94 }9596 //下面看看dataSource的解析方法97 private DataSourceFactory dataSourceElement(XNode context) throws Exception {98 if (context != null) {99 //dataSource的链接池100 String type = context.getStringAttribute("type");101 //子节点 name, value属性set进一个properties对象102 Properties props = context.getChildrenAsProperties();103 //建立dataSourceFactory104 DataSourceFactory factory = (DataSourceFactory) resolveClass(type).newInstance();105 factory.setProperties(props);106 return factory;107 }108 throw new BuilderException("Environment declaration requires a DataSourceFactory.");109 }110 }
经过以上对mybatis源码的解读,相信你们对mybatis的配置又有了一个深刻的认识。
还有一个问题, 上面咱们看到,在配置dataSource的时候使用了 ${driver} 这种表达式, 这种形式是怎么解析的?其实,是经过PropertyParser这个类解析:
PropertyParser:
/*** 这个类解析${}这种形式的表达式*/public class PropertyParser {public static String parse(String string, Properties variables) {VariableTokenHandler handler = new VariableTokenHandler(variables);GenericTokenParser parser = new GenericTokenParser("${", "}", handler);return parser.parse(string);}private static class VariableTokenHandler implements TokenHandler {private Properties variables;public VariableTokenHandler(Properties variables) {this.variables = variables;}public String handleToken(String content) {if (variables != null && variables.containsKey(content)) {return variables.getProperty(content);}return "${" + content + "}";}}}
好啦,以上就是对于properties 和 environments元素节点的分析,比较重要的都在对于源码的注释中标出。本次文章到此结束,接下来的文章会继续分析其余节点的配置。
经过以上源码,咱们就能看出,在mybatis的配置文件中:
1. configuration节点为根节点。
2. 在configuration节点之下,咱们能够配置10个子节点, 分别为:properties、typeAliases、plugins、objectFactory、objectWrapperFactory、settings、environments、databaseIdProvider、typeHandlers、mappers。
上次对于配置文件的方式是使用的是外部文件方式,若是不用外部文件,则可使用下面的方式;
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/> <property name="url" value="jdbc:sqlserver://localhost:1433;DatabaseName=mydb"/> <property name="username" value="sa"/> <property name="password" value="1"/></dataSource> </environment> </environments> <mappers> <mapper resource="org/mybatis/example/dao/DeptMapper.xml"/> </mappers> </configuration>