package com.lbx.spring;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
public class ClassPathXmlApplicationContext implements BeanFactory {
// 一个id对应一个bean
private Map<String, Object> beans = new HashMap<String, Object>();
public ClassPathXmlApplicationContext() throws Exception {
// jdom解析XML
SAXBuilder builder = new SAXBuilder();
// 开始解析XML
Document document = builder.build("beans.xml");
// 获得根元素
Element root = document.getRootElement();
// 获取根元素下的所有子元素
List lists = root.getChildren();
// 遍历所有的子元素
for (int i = 0; i < lists.size(); i++) {
Element e = (Element) lists.get(i);
String id = e.getAttributeValue("id");
// 获得bean里面的class
String class1 = e.getAttributeValue("class");
// 利用反射获得对象的实例
Object obj = Class.forName(class1).newInstance();
System.out.println(id);
System.out.println(class1);
beans.put(id, obj);
// 要是子元素中还有属性
for (Element propertyElement : (List<Element>) e
.getChildren("property")) {
// 根据属性的name
String name = propertyElement.getAttributeValue("name");
// 获得要注入的bean的id
String bean = propertyElement.getAttributeValue("ref");
// 获得要注入bean的实例(Map中根据id)
Object beanObject = beans.get(bean);
// 生成相应的set方法
String methodName = "set" + name.substring(0, 1).toUpperCase()
+ name.substring(1);
System.out.println("set方法名: " + methodName);
Method m = obj.getClass().getMethod(methodName,
beanObject.getClass().getInterfaces()[0]);
m.invoke(obj, beanObject);
}
}
}
@Override
public Object getBean(String id) {
return beans.get(id);
}
}
下面就是测试代码
package com.lbx.service;
import org.junit.Test;
import com.lbx.model.User;
import com.lbx.spring.BeanFactory;
import com.lbx.spring.ClassPathXmlApplicationContext;
public class UserServiceTest {
@Test
public void testAdd() throws Exception {
BeanFactory applicationContext = new ClassPathXmlApplicationContext();
UserService service = (UserService)applicationContext.getBean("userService");
User u = new User();
u.setUsername("lbx");
u.setPassword("123456");
service.add(u);
}
}