getBean(String name),獲取 Bean 實例。setReader 由子類決定讀取器。XMLSourceReader 並加載 Bean 定義。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 定義讀取、實例化與依賴注入的本質。