加载配置文件到字节流

首先封装一个Resources类用来加载配置文件

1
2
3
4
5
6
7
8
9
10
11
12
public class Resources {

/**
* 根据path加载配置文件
* @param path 配置文件路径
* @return InputStream
*/
public static InputStream getResourceAsStream(String path){
ClassLoader classLoader = Resources.class.getClassLoader();
return classLoader.getResourceAsStream(path);
}
}

解析XML配置文件

使用dom4j库中的SAX方式读取字节流,获取配置文件中的dom节点信息

连接信息封装到DataSource中,其他信息封装到一个List集合

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public Configuration parseConfig(InputStream in) throws Exception {
Document document = new SAXReader().read(in);
//<configuration>
Element rootElement = document.getRootElement();
List<Element> list = rootElement.selectNodes("//property");
Properties properties = new Properties();
for (Element element : list) {
String name = element.attributeValue("name");
String value = element.attributeValue("value");
properties.setProperty(name, value);
}

MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setUrl(properties.getProperty("url"));
dataSource.setUser(properties.getProperty("username"));
dataSource.setPassword(properties.getProperty("password"));
configuration.setDataSource(dataSource);
//解析mapper.xml
//拿到路径
List<Element> mapperList = rootElement.selectNodes("//mappers");
//获得流并解析
for (Element element : mapperList) {
String mapperPath = element.attributeValue("resource");
InputStream mapperStream = Resources.getResourceAsStream(mapperPath);
XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
xmlMapperBuilder.parse(mapperStream);
}
return configuration;
}

这里使用了一个Properties对象来封装每一条K/V。

解析mapper.xml信息

映射配置文件格式类似MyBatis,使用一个namespace来区别不同的包,然后每一条sql都使用相应的标签包裹。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public void parse(InputStream inputStream) throws Exception {
Document document = new SAXReader().read(inputStream);
Element rootElement = document.getRootElement();
String namespace = rootElement.attributeValue("namespace");
List<Element> selectList = rootElement.selectNodes("//select");
for (Element element : selectList) {
//获取每个属性
String id = element.attributeValue("id");
String resultType = element.attributeValue("resultType");
String paramType = element.attributeValue("paramType");
String sqlText = element.getTextTrim();
//封装到MappedStatement
MappedStatement statement = new MappedStatement();
statement.setId(id);
statement.setResultType(resultType);
statement.setParamType(paramType);
statement.setSql(sqlText);
String key = namespace + "." + id;
//保存在map中
configuration.getMappedStatementMap().put(key, statement);
}
}