<!-- 組織機構管理 -->
<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>
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, pkg, entity, callString);
}
} catch (Exception e1) {
e1.printStackTrace();
}
}