首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

手把手實現簡易 Spring IOC 容器:Bean 定義、XML 解析與依賴注入流程

     編輯:Java 綜合教學

簡易 Spring IOC 容器實現

核心類設計

  • BeanFactory 接口: 定義 getBean(String name),獲取 Bean 實例。
  • AbstractBeanFactory 抽象類: 實現 Bean 解析邏輯(反射實例化、屬性注入),模板方法 setReader 由子類決定讀取器。
  • XMLContext: 繼承 AbstractBeanFactory,構造時指定 XMLSourceReader 並加載 Bean 定義。
  • BeanInfo: 存儲 Bean 的 id、class、properties(map)。
  • SourceReader 接口 & XMLSourceReader: 使用 Dom4j 解析 XML,利用 Java 內省 Introspector 獲取屬性描述符,反射調用 setter 注入值。

類結構圖

關鍵代碼片段

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

// 抽象工廠實現解析邏輯
protected Object parseBean(BeanInfo beanInfo) {
    Class clazz = Class.forName(beanInfo.getType());
    Object bean = clazz.newInstance();
    for (String prop : beanInfo.getProperties().keySet()) {
        String setter = "set" + firstCharToUp(prop);
        for (Method m : clazz.getDeclaredMethods()) {
            if (m.getName().equals(setter)) {
                m.invoke(bean, beanInfo.getProperties().get(prop));
            }
        }
    }
    return bean;
}

// XML 讀取器核心邏輯
public Map<String, BeanInfo> loadBeans(String filePath) {
    SAXReader reader = new SAXReader();
    InputStream ins = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath);
    Document doc = reader.read(ins);
    Element root = doc.getRootElement();
    Map<String, BeanInfo> map = new HashMap<>();
    for (Iterator i = root.elementIterator("bean"); i.hasNext(); ) {
        Element el = (Element) i.next();
        String id = el.attributeValue("id");
        String cls = el.attributeValue("class");
        Class beanClass = Class.forName(cls);
        BeanInfo info = new BeanInfo();
        info.setId(id); info.setType(cls);
        for (Iterator it = el.elementIterator("property"); it.hasNext(); ) {
            Element propEl = (Element) it.next();
            String name = propEl.attributeValue("name");
            String value = propEl.elementText("value");
            info.addProperty(name, value);
        }
        map.put(id, info);
    }
    return map;
}

使用示例

XMLContext ctx = new XMLContext("beans.xml");
MyService service = (MyService) ctx.getBean("myService");
service.doSomething();

通過模擬核心流程,深入理解 Spring IOC 容器啟動、Bean 定義讀取、實例化與依賴注入的本質。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved