版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013967628/article/details/81043016
Spring Ioc就是对java反射及读取xml文件的使用的封装
public interface BeanFactory {
public Object getBean(String id);
}
public class ClassPathXmlApplicationContext implements BeanFactory {
// 存储解析xml后各个实例的键值对
private Map<String, Object> beans = new HashMap<String, Object>();
public ClassPathXmlApplicationContext() throws Exception {
SAXBuilder sb = new SAXBuilder();// 读取XML文件
Document doc = sb.build(this.getClass().getClassLoader().getResourceAsStream("beans.xml"));
Element root = doc.getRootElement();
List list = root.getChildren("bean");
for (int i = 0; i < list.size(); i++) {
Element element = (Element) list.get(i);
String id = element.getAttributeValue("id");
String clazz = element.getAttributeValue("class");
// 利用反射生成类对象保存到beans
Object o = Class.forName(clazz).newInstance();
beans.put(id, o);
// 对bena下的property元素遍历
for (Element propertyElement : (List<Element>) element.getChildren("property")) {
String name = propertyElement.getAttributeValue("name");
String beanInstance = propertyElement.getAttributeValue("bean");
// 取得注入的实例
Object beanObject = beans.get(beanInstance);
// 获取属性set方法
String methodName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1);
Method m = o.getClass().getMethod(methodName, beanObject.getClass());
m.invoke(o, beanObject);
}
}
}
@Override
public Object getBean(String id) {
return beans.get(id);
}
}
测试类
public class Test {
public static void main(String[] args) throws Exception {
ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext();
Whr whr = (Whr) app.getBean("whr");
whr.print();
}
}
实体类
public class BMWCar {
public void print() {
System.out.println("hhh");
}
}
public class Whr {
public BMWCar bmWCar;
public void setBmWCar(BMWCar bmWCar) {
this.bmWCar = bmWCar;
}
public void print() {
bmWCar.print();
}
}