beans.xml:
<beans>
<bean id="u" class="com.bjsxt.dao.impl.UserDAOImpl" />
<bean id="userService" class="com.bjsxt.service.UserService" >
<property name="userDAO" bean="u"/>
</bean>
</beans>
ClassPathXmlApplicationContext.java
package com.bjsxt.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 {
// 定义容器用于存放<bean> ,需要用时从容器中来取
private Map<String , Object> beans = new HashMap<String, Object>();
//IOC Inverse of Control DI Dependency Injection
public ClassPathXmlApplicationContext() throws Exception {
SAXBuilder sb=new SAXBuilder();
//构造文档对象
Document doc=sb.build(this.getClass().getClassLoader().getResourceAsStream("beans.xml"));
//获取根元素HD
Element root=doc.getRootElement();
//取名字为bean的所有元素
List list=root.getChildren("bean");
//*******************************************************************
// 将 配置文件里的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");
Object o = Class.forName(clazz).newInstance();
System.out.println(id+"111");
System.out.println(clazz);
beans.put(id, o);
//************************************
// 将对应的<property > 注入
for(Element propertyElement : (List<Element>)element.getChildren("property")) {
String name = propertyElement.getAttributeValue("name"); //userDAO
String bean = propertyElement.getAttributeValue("bean"); //u
Object beanObject = beans.get(bean);//UserDAOImpl instance
// 组装出对应的set方法
String methodName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1);
System.out.println("method name = " + methodName);
Method m = o.getClass().getMethod(methodName, beanObject.getClass().getInterfaces()[0]);
// 调用set方法初始化对应的property
m.invoke(o, beanObject);
}
}
}
@Override
public Object getBean(String id) {
return beans.get(id);
}
}
程序一启动,就将配置文件里的bean全部初始化放到容器里;要用的时候直接从容器里取
<beans>
<bean id="u" class="com.bjsxt.dao.impl.uerDAOImpl">
<bean id="userService" class="com.bjsxt.service.UserService">
<property name="userDAO" bean="u" />
</bean>
</beans>
在userService里有个属性叫userDAO
其中的<property> 对应着set...方法
spring可以动态的装配,可以将<property > 注入进来