对spring框架的学习我是从模拟它的简单实现开始,这样也易于领悟到它的整个框架结构,以下是简单实现的代码:
配置文件:spring.xml
<?xml version="1.0" encoding="UTF-8"?> <beans> <bean id="beanId" class="pojo.Unit"> <property name="name" value="cxhappyday"/> <property name="value" value="hello world!"/> </bean> </beans> |
程序入口:myspring.java
public class myspring { public static void main(String[] args) throws Exception{ Unit unit = (Unit)(BeanFactory.getBean("D:\……mytest\src\test\sprint.xml", "beanId")); System.out.print("unit is "+unit.toString()+",name:"+unit.getName()+",value:"+unit.getValue()); } } |
实例:Unit.java
public class Unit { private String name; // 注意这里的name与以上xml文件的name是对用关系(必须相同) private String value; // 同上 public Unit(){ System.out.print("create Unit object
"); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } |
对象实例化的实现类:BeanFactory.java
package test; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.util.List; import org.apache.commons.beanutils.BeanUtils; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class BeanFactory { // 获取实例化后的对象 static public Object getBean(String path,String nodeName) throws DocumentException, InstantiationException, IllegalAccessException, ClassNotFoundException, InvocationTargetException{ Document document = loadXml(path); Element nodeElement = getNodeElement(document,nodeName); Object obj = reflectObject(nodeElement); setObjectAttr(obj,nodeElement); return obj; } // 加载xml文件 static public Document loadXml(String path) throws DocumentException { SAXReader read = new SAXReader(); return read.read(new File(path)); } // 根据以上xml文件中配置的类全路径(pojo.Unit)使用反射得到实例 static public Object reflectObject(Element node) throws InstantiationException, IllegalAccessException, ClassNotFoundException{ return Class.forName(node.attributeValue("class")).newInstance(); } static public Element getNodeElement(Document doc,String name){ String nodeName = "//bean[@id='"+name+"']"; return (Element)doc.selectSingleNode(nodeName); } // 根据spring.xml中的配置设置Unit对象的属性值即name和value的值 static public void setObjectAttr(Object obj,Element element) throws IllegalAccessException, InvocationTargetException{ List<Element> list = element.elements("property"); for (Element node:list){ String name = node.attributeValue("name"); String value = node.attributeValue("value"); // 这里关注下 BeanUtils工具类的使用 BeanUtils.setProperty(obj, name, value); } } } |
最后说下运行该程序需要的几个Jar包:
1、commons-beanutils-1.8.0.jar:BeanUtils类在该Jar中负责给对象属性赋值;
2、commons-logging.jar:commons-beanutils-1.8.0.jar对它依赖;
3、dom4j-1.6.1.jar:负责解析XML文件;
4、jaxen-1.1-beta-6.jar:dom4j-1.6.1.jar依赖它;