理解Spring架構---利用,xml,java反射簡單實現Spring__spring

來源:互聯網
上載者:User

對於Spring架構的簡單類比:

     a).讀取xml設定檔

     b.)利用java反射機制擷取對象


第一步:建立一個介面,定義一個擷取對象的方法getBean():

public interface BeanFactory {public  Object  getBean(String name);}


第二步:建立一個類XmlContext,實現Beanfactory介面中的getBean方法:

public class XmlContext implements BeanFactory {// 對象名加對象執行個體private Map<String, Object> beans = new HashMap<String, Object>();// 利用jdom讀取xml檔案擷取對象名,通過反射擷取對象public XmlContext() throws Exception {SAXBuilder builder = new SAXBuilder();InputStream file = new FileInputStream("test.xml");Document document = builder.build(file);// 獲得文檔對象Element root = document.getRootElement();// 獲得根節點List<Element> list = root.getChildren();for (Element elements : list) {// 擷取屬性值,即為對象的名字String ObjectName = elements.getAttributeValue("id");// 在擷取類的路徑,在通過java反射擷取類的類類型,在擷取該類的對象String classpath = elements.getAttributeValue("class");Object obj = Class.forName(classpath).newInstance();beans.put(ObjectName, obj);// 擷取子節點下的property節點List<Element> eles = elements.getChildren("property");// 進行遍曆for (Element e : eles) {String proName = e.getAttributeValue("name");Object beanObj = this.getBean(e.getAttributeValue("bean"));System.out.println(beanObj.toString());// 然後調用service的構造方法String methodName = "set"+ proName.substring(0, 1).toUpperCase()+ proName.substring(1);System.out.println("methodName:" + methodName);// 通過反射擷取構造方法Method method = obj.getClass().getMethod(methodName,beanObj.getClass().getInterfaces()[0]);method.invoke(obj, beanObj);}}}@Overridepublic Object getBean(String name) {return beans.get(name);}}





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.