SpringIOC容器手写( 一)--XML文件解析
2019-01-19 本文已影响0人
aix91
1. 安装Dom4j包
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
2. Element:
<bean id="mainJedisConnFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
element.getName() = 'bean'
3. Attribute
Attribute 是Element下面的键值对,如"id"是 attribute de name,"mainJedisConnFactory"是attribute 的 data。
4. 实例
- 提取Element
public void parseXml() {
SAXReader reader = new SAXReader();
try {
Document document = reader.read(getResourceAsStream("redis.xml"));
Element rootElement = document.getRootElement();
List<Element> beans = rootElement.elements("bean");
for (Element bean : beans) {
System.out.println(bean.getName());
printAttrs(bean);
List<Element> props = bean.elements("property");
props.forEach(p->printAttrs(p));
}
} catch (DocumentException e) {
e.printStackTrace();
}
}
- 提取Element下的Attribute
public void printAttrs(Element element){
List<Attribute> attrs = element.attributes();
for (Attribute attr : attrs) {
System.out.println(attr.getName() + " => " + attr.getData());
}
}
- 输出
bean
id => mainJedisConnFactory
class => org.springframework.data.redis.connection.jedis.JedisConnectionFactory
name => hostName
value => ${redis.main.host}
name => port
value => ${redis.main.port}
name => password
value => ${redis.main.password}
name => database
value => ${redis.main.db}
name => timeout
value => ${redis.main.timeout}
name => usePool
value => true
bean
id => mainRedisTemplate
class => org.springframework.data.redis.core.RedisTemplate
name => connectionFactory
ref => mainJedisConnFactory