Spring读取配置文件原理(Spring如何依赖注入的)
初学Spring,spring依赖注入的原理
IOC(DI)
Inverse of Control 控制反转最好的解释是Dependency Injection依赖注入
?
beans.xml(模拟spring的配置文件)代码如下:
<beans>
?<bean id="userDao" />
?<bean id="userService" bean="userDao" />
?</bean>
</beans>
?
BeanFactory.java(bean的工厂)代码如下:
package com.spring;
public interface BeanFactory {
?public Object getBean(String name);
}
ClassPathXmlApplicationContext.java (解析配置文件的累实现bean工厂接口)代码如下:
package com.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{
?
?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().getResource("beans.xml"));
??Element root = doc.getRootElement();//获取根元素beans
??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 obj =Class.forName(clazz).newInstance();
???System.out.println(id);
???System.out.println(clazz);
???beans.put(id, obj);
???
???for(Element propertyElement : (List<Element>)element.getChildren("property")) {
????String name = propertyElement.getAttributeValue("name");//获取name=userDao中的userDao
????String bean = propertyElement.getAttributeValue("bean");//获取dao的bean
????Object beanObject = beans.get(bean);//userDaoImpl instance
????
????String methodName = "set"+name.substring(0,1).toUpperCase()+name.substring(1);
????System.out.println("method name:"+methodName);
????Method m = obj.getClass().getMethod(methodName, beanObject.getClass().getInterfaces()[0]);//setUserDao(UserDao.class)
????m.invoke(obj, beanObject);
????
???}
??}
?}
?
?public Object getBean(String name) {
??return beans.get(name);
?}
}
测试类代码如下:
package com.test;
import com.model.User;
import com.service.UserService;
import com.spring.BeanFactory;
import com.spring.ClassPathXmlApplicationContext;
public class UserServiceTest {
?
?public static void main(String[] args) throws Exception {
???? BeanFactory factory = new ClassPathXmlApplicationContext();
??? // UserDao dao = (UserDao) factory.getBean("userDao");
???? User user = new User();
???? user.setPassword("sss");
??? // dao.save(user);
???? UserService service = (UserService)factory.getBean("userService");
???? service.add(user);
?}
}
注释:service层,dao层,实体层的代码没给出在下面的spring读取配置文件.rar中有源码并带有jdom的jar包!!
1 楼 nurenok 2011-12-15 谢谢,非常好