dom4j解析spring.xml

1.spring.xml如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">


  <bean id="hello" class="com.yc.spring.Hello">
  <property name="word" value="你好!"></property>
  </bean>
</beans>


2.类方法如下:

package com.yc.spring;

import com.yc.spring.core.MyClassPathXmlApplicationContext;


public class Hello {
private String word;
public void setWord(String word) {
this.word = word;
}

public void say(){
System.out.println("我说:"+word);
}

public static void main(String[] args) {
MyClassPathXmlApplicationContext mc=new MyClassPathXmlApplicationContext("spring.xml");
Hello hello=(Hello) mc.getBean("hello");
hello.say();
}

}

3.解析

package com.yc.spring.core;


import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;


public class MyClassPathXmlApplicationContext {
private Map<String, Object> beans;//spring容器,存放所有bean对象


public MyClassPathXmlApplicationContext(String config) {
beans=new HashMap<String,Object>();
parseConfig(config);
}


public void parseConfig(String config) {
try {
SAXReader reader=new SAXReader();//创建解析对象
InputStream in=MyClassPathXmlApplicationContext.class.getClassLoader().getResourceAsStream(config);
Document doc=reader.read(in);//解析配置文件流

Element root=doc.getRootElement();//取到Document根(beans)

List<Element> bs=root.elements();//取到所有的beans元素

for (Element b : bs) {
String id=b.attributeValue("id");
String className=b.attributeValue("class");
Class beanClass=Class.forName(className);//取到bean类的类对象
Object beanObj = beanClass.newInstance();//取到bean的对象
List<Element> ps=b.elements();
for (Element p: ps) {
String name=p.attributeValue("name");
String value=p.attributeValue("value");
String methodName="set"+name.substring(0,1).toUpperCase()+name.substring(1);//对应属性的setXXX方法
Method m=beanClass.getMethod(methodName, String.class);//取到方法对象
m.invoke(beanObj, value);//通过反射调用方法给属性注值
}
beans.put(id, beanObj);
}
} catch (Exception e) {
e.printStackTrace();
}
}

//通过bean 的id,取到bean 对象
public Object getBean(String beanId){
return beans.get(beanId);
}
}


4.测试结果




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值