加载配置文件到字节流
首先封装一个Resources类用来加载配置文件
1 2 3 4 5 6 7 8 9 10 11 12
| public class Resources {
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); 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); 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 statement = new MappedStatement(); statement.setId(id); statement.setResultType(resultType); statement.setParamType(paramType); statement.setSql(sqlText); String key = namespace + "." + id; configuration.getMappedStatementMap().put(key, statement); } }
|