标签:
一,分层
UserService层:业务逻辑层 UserDAO:仅仅和数据库打交道、
二,xml文件的读取
<!--test.xml--!> <?xml version="1.0" encoding="UTF-8"?> <HD> <disk name="C"> <capacity>8G</capacity> <directories>200</directories> <files>1580</files> </disk> <disk name="D"> <capacity>10G</capacity> <directories>500</directories> <files>3000</files> </disk> </HD>
//sample.java import java.util.*; import org.jdom.*; import org.jdom.input.SAXBuilder; public class Sample { public static void main(String[] args) throws Exception{ SAXBuilder sb=new SAXBuilder(); Document doc=sb.build(Sample.class.getClassLoader().getResourceAsStream("test.xml")); //构造文档对象 Element root=doc.getRootElement(); //获取根元素HD List list=root.getChildren("disk");//取名字为disk的所有元素 for(int i=0;i<list.size();i++){ Element element=(Element)list.get(i); /*String id=element.getAttributeValue("id"); String clazz=element.getAttributeValue("class"); System.out.println(id); System.out.println(clazz);*/ String name=element.getAttributeValue("name"); String capacity=element.getChildText("capacity");//取disk子元素capacity的内容 String directories=element.getChildText("directories"); String files=element.getChildText("files"); System.out.println("磁盘信息:"); System.out.println("分区盘符:"+name); System.out.println("分区容量:"+capacity); System.out.println("目录数:"+directories); System.out.println("文件数:"+files); System.out.println("-----------------------------------"); } } }
三,xml中bean的读取
public class ClassPathXmlApplicationContext implements BeanFactory { private Map<String, Object> beans=new HashMap<String, Object>(); public ClassPathXmlApplicationContext() throws Exception{ SAXBuilder sBuilder=new SAXBuilder(); Document document=sBuilder.build(this.getClass().getClassLoader().getResourceAsStream("beans.xml")); Element root=document.getRootElement(); List list=root.getChildren("bean"); for(int i=0;i<list.size();i++){ Element element=(Element)list.get(i); String id=element.getAttributeValue("id"); String clazz=element.getAttributeValue("class"); Object o=Class.forName(clazz).newInstance(); System.out.println(id); System.out.println(clazz); beans.put(id, o); for(Element propertyElement : (List<Element>)element.getChildren("property")) { String name = propertyElement.getAttributeValue("name"); //userDAO String bean = propertyElement.getAttributeValue("bean"); //u Object beanObject = beans.get(bean);//UserDAOImpl instance String methodName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1); System.out.println("method name = " + methodName); //反射机制 Method m = o.getClass().getMethod(methodName, beanObject.getClass().getInterfaces()[0]); m.invoke(o, beanObject); } } } public Object getBean(String id){ return beans.get(id); } }
四,什么是IOC(DI)
IOC:控制反转,
DI:依赖注入
1,把自己new的东西改为容器提供
初始化具体值。
装配
2,好处:灵活装配
标签:
原文地址:http://www.cnblogs.com/enjoy-life-clh/p/4214294.html