您的位置:首页 > 编程语言 > Java开发

dom4j解析spring.xml

2016-04-25 19:18 543 查看
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.测试结果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: