MyBatis-3.4.2-源码分析8:XML解析之environmentsElement(root.evalNode("environments"))

下面,开始讲解environments。

private void environmentsElement(XNode context) throws Exception {
		// 如果定义了
		if (context != null) {
			//设置environment为default属性
			if (environment == null) {
				environment = context.getStringAttribute("default");
			}
			//开始遍历每1个子节点
			for (XNode child : context.getChildren()) {
				//获得id属性值
				String id = child.getStringAttribute("id");
				//如果是特定的,也就是跟environment值一样的,才解析
				//那么设置多个干嘛?
				if (isSpecifiedEnvironment(id)) {
					//如果条件一致
					//开始构建事务工厂
					TransactionFactory txFactory = transactionManagerElement(child.evalNode("transactionManager"));
					DataSourceFactory dsFactory = dataSourceElement(child.evalNode("dataSource"));
					DataSource dataSource = dsFactory.getDataSource();
					Environment.Builder environmentBuilder = new Environment.Builder(id).transactionFactory(txFactory)
							.dataSource(dataSource);
					configuration.setEnvironment(environmentBuilder.build());
				}
			}
		}
	}

下面是构建transactionManagerElement的过程。

private TransactionFactory transactionManagerElement(XNode context) throws Exception {
		//开始构建
		//如果节点存在
		if (context != null) {
			//读取type的属性值
			String type = context.getStringAttribute("type");
			//获取属性值,为了后面填充
			Properties props = context.getChildrenAsProperties();
			//根据别名,构建实例
			TransactionFactory factory = (TransactionFactory) resolveClass(type).newInstance();
			//然后呢?对于JDBC类型的来说,完全不起作用,所以不用配置了
			factory.setProperties(props);
			//返回结果
			return factory;
		}
		throw new BuilderException("Environment declaration requires a TransactionFactory.");
		//结束
	}

继续处理

//继续处理,构造数据源系统
					DataSourceFactory dsFactory = dataSourceElement(child.evalNode("dataSource"));
					DataSource dataSource = dsFactory.getDataSource();
					Environment.Builder environmentBuilder = new Environment.Builder(id).transactionFactory(txFactory)
							.dataSource(dataSource);
					configuration.setEnvironment(environmentBuilder.build());

看看数据源怎么构建的

	private DataSourceFactory dataSourceElement(XNode context) throws Exception {
		//如果设置了dataSource属性
		if (context != null) {
			//提取type的值
			String type = context.getStringAttribute("type");
			//提取子节点作为属性
			Properties props = context.getChildrenAsProperties();
			//根据type来构建实例
			DataSourceFactory factory = (DataSourceFactory) resolveClass(type).newInstance();
			//使用属性
			factory.setProperties(props);
			return factory;
			//结束
		}
		throw new BuilderException("Environment declaration requires a DataSourceFactory.");
		//返回
	}

 

转载于:https://my.oschina.net/qiangzigege/blog/868784

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值