init.XML文档
<?xml version="1.0" encoding="UTF-8"?>
<init package="com.oa.model"><!-- 组织机构管理 -->
<entity class= "Company"
name = "大学"
description = "塞上明珠"
call = "partyService.addParty">
<entity class="Department" name="教务处">
<entity class="Position" name="教务处处长">
<entity class="Person" name="张三" sex="男" tel="1111">
</entity>
</entity>
<entity class="Position" name="教务处副处长">
<entity class="Person" name="李四" sex="女" tel="1222">
</entity>
</entity>
</entity>
<entity class="Department" name="图书馆">
<entity class="Position" name="图书馆馆长">
<entity class="Person" name="王五" sex="女" tel="2222">
</entity>
<entity class="Person" name="赵六" sex="男" tel="2111">
</entity>
</entity>
</entity>
<entity class="Company" name="大学南校区"></entity>
</entity>
</init>
//解析方法
public void addInitData() { try { //解析init.xml文档 Document doc = new SAXReader().read(Thread.currentThread().getContextClassLoader().getResourceAsStream(init.xml)); //得到根元素 Element root = doc.getRootElement(); //得到包名 String pkg = root.valueOf("@package"); //得到根元素下的entity集合 List<Element> entities = root.selectNodes("entity"); for(Iterator<Element> iter = entities.iterator() ; iter.hasNext();){ Element e = iter.next(); addEntity(e,pkg,null,null); } } catch (Exception e) { e.printStackTrace(); } } private void addEntity(Element e,String pkg,Object parent,String callString) { try { //处理当前Element // 1. 要创建一个什么样类型的对象 //要创建类的全包名 String className = pkg + "." + e.attributeValue("class"); //根据类名创建实体对象 Object entity = Class.forName(className).newInstance(); //给实体对象当中的属性赋值 Iterator iter = e.attributeIterator(); while(iter.hasNext()){ Attribute attr = (Attribute)iter.next(); String propName = attr.getName(); //判断除了class和call属性的其它属性赋值 if(!"class".equals(propName) && !"call".equals(propName)){ String propValue = attr.getValue(); BeanUtils.copyProperty(entity,propName,propValue); } } //给entity父实体属性赋值 BeanUtils.copyProperty(entity,"parent",parent); // 2. 存储对象(调用哪一个Service的哪一个方法?) String call = e.attributeValue("call"); if(call != null){ callString = call; } if(callString == null){ throw new RuntimeException("无法创建实体对象,调用方法未知!"); } // 3. 调用相应的方法存储实体 String[] mesg = callString.split("\\."); String serviceName = mesg[0]; String methodName = mesg[1]; //得到Service对象 Object serviceObject = factory.getBean(serviceName); //得到要调用的Servce对象上的方法的反射类 for(Method m : serviceObject.getClass().getMethods()){ if(methodName.equals(m.getName())){ //调用这个方法 m.invoke(serviceObject,entity); } } // 4. 考虑当前Element下有没有子元素 List<Element> subEntities = e.elements("entity"); for(Iterator<Element> itr = subEntities.iterator(); itr.hasNext();){ Element subElement = itr.next(); addEntity(subElement,entity,callString); } } catch (Exception e1) { e1.printStackTrace(); } }
原文链接:https://www.f2er.com/xml/299753.html