Spring的IOC机制

         IOC,直观地讲,就是容器控制程序之间的关系,而非传统实现中,由程序代码直接操控。这也就是所谓“控制反转”的概念所在。控制权由应用代码中转到了外部容器,控制权的转移是所谓反转。IoC还有另外一个名字——“依赖注入(Dependency Injection)”。从名字上理解,所谓依赖注入,即组件之间的依赖关系由容器在运行期决定,形象地说,即由容器动态地将某种依赖关系注入到组件之中。 

 
        下面我根据spring源码 简单实现自己的依赖注入  通过xml形式配置   在对象中获取xml文件 获取定义好的bean 从而对bean对应的class 实现实例化   使用接口形式

 

接口

 

Java代码 复制代码  收藏代码
  1. public interface PersonDao {   
  2.   
  3.     public void add();   
  4.   
  5. }  
public interface PersonDao {

	public void add();

}
 

实现类

Java代码 复制代码  收藏代码
  1. package cn.leam.dao.impl;   
  2.   
  3. import cn.leam.dao.PersonDao;   
  4.   
  5. public class PersonDaoBean implements PersonDao {   
  6.     public void add(){   
  7.         System.out.println("执行add()方法");   
  8.     }   
  9. }  
package cn.leam.dao.impl;

import cn.leam.dao.PersonDao;

public class PersonDaoBean implements PersonDao {
	public void add(){
		System.out.println("执行add()方法");
	}
}
 

服务接口

Java代码 复制代码  收藏代码
  1. public interface PersonService {   
  2.   
  3.     public void save();   
  4.   
  5. }  
public interface PersonService {

	public void save();

}

 

服务实现类

Java代码 复制代码  收藏代码
  1. public class PersonServiceBean implements PersonService {   
  2.     private PersonDao personDao;   
  3.        
  4.     public PersonDao getPersonDao() {   
  5.         return personDao;   
  6.     }   
  7.   
  8.     public void setPersonDao(PersonDao personDao) {   
  9.         this.personDao = personDao;   
  10.     }   
  11.        
  12.     public void save(){   
  13.         personDao.add();   
  14.     }   
  15. }  
public class PersonServiceBean implements PersonService {
	private PersonDao personDao;
	
	public PersonDao getPersonDao() {
		return personDao;
	}

	public void setPersonDao(PersonDao personDao) {
		this.personDao = personDao;
	}
	
	public void save(){
		personDao.add();
	}
}
 

 

首先配置beans.xml    配置DAO,SERVICE实现类

 

Xml代码 复制代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.        xsi:schemaLocation="http://www.springframework.org/schema/beans   
  5.            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">  
  6.            <bean id="personDao" class="cn.leam.dao.impl.PersonDaoBean"></bean>  
  7.           <bean id="personService" class="cn.leam.service.impl.PersonServiceBean">  
  8.             <property name="personDao" ref="personDao"></property>  
  9.           </bean>  
  10. </beans>  
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
           <bean id="personDao" class="cn.leam.dao.impl.PersonDaoBean"></bean>
          <bean id="personService" class="cn.leam.service.impl.PersonServiceBean">
          	<property name="personDao" ref="personDao"></property>
          </bean>
</beans>
 

 

 

下面模拟spring对xml配置的类进行实例化

 

存放属性的对象

Java代码 复制代码  收藏代码
  1. public class prosDefinition {   
  2.     private String name;   
  3.     private String ref;   
  4.        
  5.     public ProsDefinition(String name, String ref) {   
  6.         this.name = name;   
  7.         this.ref = ref;   
  8.     }   
  9.        
  10.     public String getName() {   
  11.         return name;   
  12.     }   
  13.     public void setName(String name) {   
  14.         this.name = name;   
  15.     }   
  16.     public String getRef() {   
  17.         return ref;   
  18.     }   
  19.     public void setRef(String ref) {   
  20.         this.ref = ref;   
  21.     }   
  22.        
  23. }  
public class prosDefinition {
	private String name;
	private String ref;
	
	public ProsDefinition(String name, String ref) {
		this.name = name;
		this.ref = ref;
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getRef() {
		return ref;
	}
	public void setRef(String ref) {
		this.ref = ref;
	}
	
}
 

 

存放bean的 对象

Java代码 复制代码  收藏代码
  1. public class Definition {   
  2.     private String id;   
  3.     private String className;   
  4.     private List<ProsDefinition> propertys = new ArrayList<ProsDefinition>();   
  5.        
  6.     public Definition(String id, String className) {   
  7.         this.id = id;   
  8.         this.className = className;   
  9.     }   
  10.     public String getId() {   
  11.         return id;   
  12.     }   
  13.     public void setId(String id) {   
  14.         this.id = id;   
  15.     }   
  16.     public String getClassName() {   
  17.         return className;   
  18.     }   
  19.     public void setClassName(String className) {   
  20.         this.className = className;   
  21.     }   
  22.     public List<PropertyDefinition> getPropertys() {   
  23.         return propertys;   
  24.     }   
  25.     public void setPropertys(List<PropertyDefinition> propertys) {   
  26.         this.propertys = propertys;   
  27.     }   
  28.        
  29. }  
public class Definition {
	private String id;
	private String className;
	private List<ProsDefinition> propertys = new ArrayList<ProsDefinition>();
	
	public Definition(String id, String className) {
		this.id = id;
		this.className = className;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getClassName() {
		return className;
	}
	public void setClassName(String className) {
		this.className = className;
	}
	public List<PropertyDefinition> getPropertys() {
		return propertys;
	}
	public void setPropertys(List<PropertyDefinition> propertys) {
		this.propertys = propertys;
	}
	
}
 

 

这里是关键点  所有代码都在这里    使用dom4j 解析xml文件中的bean  并获取id和class  再判断元素中是否有引用元素对其一并获取出来存放才Map中 利用java反射一个一个进行实例化

Java代码 复制代码  收藏代码
  1. /**  
  2.  * 学习版容器  
  3.  *  
  4.  */  
  5. public class LeamClassPathXMLApplicationContext {   
  6.     private List<Definition> beanDefines = new ArrayList<Definition>();   
  7.     private Map<String, Object> sigletons = new HashMap<String, Object>();   
  8.        
  9.     public LeamClassPathXMLApplicationContext(String filename){   
  10.         this.readXML(filename);   
  11.         this.instanceBeans();   
  12.         this.injectObject();   
  13.     }   
  14.     /**  
  15.      * 为bean对象的属性注入值  
  16.      */  
  17.     private void injectObject() {   
  18.         for(Definition beanDefinition : beanDefines){   
  19.             Object bean = sigletons.get(beanDefinition.getId());   
  20.             if(bean!=null){   
  21.                 try {   
  22.                     PropertyDescriptor[] ps = Introspector.getBeanInfo(bean.getClass())   
  23.                                                       .getPropertyDescriptors();   
  24.                     for(ProsDefinition propertyDefinition : beanDefinition.getPropertys()){   
  25.                         for(PropertyDescriptor properdesc : ps){   
  26.                         if(propertyDefinition.getName().equals(properdesc.getName())){   
  27.                                 Method setter = properdesc.getWriteMethod();   
  28.                                     //获取属性的setter方法 ,private   
  29.                                 if(setter!=null){   
  30.                                 Object value = sigletons.get(propertyDefinition.getRef());   
  31.                                 setter.invoke(bean, value);//把引用对象注入到属性   
  32.                                 }   
  33.                                 break;   
  34.                             }   
  35.                         }   
  36.                     }   
  37.                 } catch (Exception e) {   
  38.                 }   
  39.             }   
  40.         }   
  41.     }   
  42.     /**  
  43.      * 完成bean的实例化  
  44.      */  
  45.     private void instanceBeans() {   
  46.         for(Definition beanDefinition : beanDefines){   
  47.             try {   
  48.                 if(beanDefinition.getClassName()!=null && !"".   
  49.                                    equals(beanDefinition.getClassName().trim()))   
  50.                               sigletons.put(beanDefinition.getId(),    
  51.                                   Class.forName(beanDefinition.getClassName()).newInstance());   
  52.             } catch (Exception e) {   
  53.                 e.printStackTrace();   
  54.             }   
  55.         }   
  56.            
  57.     }   
  58.     /**  
  59.      * 读取xml配置文件  
  60.      * @param filename  
  61.      */  
  62.     private void readXML(String filename) {   
  63.            SAXReader saxReader = new SAXReader();      
  64.             Document document=null;      
  65.             try{   
  66.              URL xmlpath = this.getClass().getClassLoader().getResource(filename);   
  67.              document = saxReader.read(xmlpath);   
  68.              Map<String,String> nsMap = new HashMap<String,String>();   
  69.              nsMap.put("ns","http://www.springframework.org/schema/beans");//加入命名空间   
  70.                  //创建beans/bean查询路径         
  71.                 XPath xsub = document.createXPath("//ns:beans/ns:bean");   
  72.              xsub.setNamespaceURIs(nsMap);//设置命名空间   
  73.              List<Element> beans = xsub.selectNodes(document);//获取文档下所有bean节点    
  74.              for(Element element: beans){   
  75.                 String id = element.attributeValue("id");//获取id属性值   
  76.                 String clazz = element.attributeValue("class"); //获取class属性值           
  77.                 BeanDefinition beanDefine = new BeanDefinition(id, clazz);   
  78.                 XPath propertysub =  element.createXPath("ns:property");   
  79.                 propertysub.setNamespaceURIs(nsMap);//设置命名空间   
  80.                 List<Element> propertys = propertysub.selectNodes(element);   
  81.                 for(Element property : propertys){                     
  82.                         //元素内部引用的属性也获取   
  83.                     String propertyName = property.attributeValue("name");   
  84.                     String propertyref = property.attributeValue("ref");   
  85.                     ProsDefinition propertyDefinition =    
  86.                          new ProsDefinition(propertyName, propertyref);   
  87.                     beanDefine.getPropertys().add(propertyDefinition);   
  88.                 }   
  89.                 beanDefines.add(beanDefine);   
  90.              }    
  91.             }catch(Exception e){      
  92.                 e.printStackTrace();   
  93.             }   
  94.     }   
  95.     /**  
  96.      * 获取bean实例  
  97.      * @param beanName  
  98.      * @return  
  99.      */  
  100.     public Object getBean(String beanName){   
  101.         return this.sigletons.get(beanName);   
  102.     }   
  103. }  
/**
 * 学习版容器
 *
 */
public class LeamClassPathXMLApplicationContext {
	private List<Definition> beanDefines = new ArrayList<Definition>();
	private Map<String, Object> sigletons = new HashMap<String, Object>();
	
	public LeamClassPathXMLApplicationContext(String filename){
		this.readXML(filename);
		this.instanceBeans();
		this.injectObject();
	}
	/**
	 * 为bean对象的属性注入值
	 */
	private void injectObject() {
		for(Definition beanDefinition : beanDefines){
			Object bean = sigletons.get(beanDefinition.getId());
			if(bean!=null){
				try {
					PropertyDescriptor[] ps = Introspector.getBeanInfo(bean.getClass())
                                                      .getPropertyDescriptors();
					for(ProsDefinition propertyDefinition : beanDefinition.getPropertys()){
						for(PropertyDescriptor properdesc : ps){
						if(propertyDefinition.getName().equals(properdesc.getName())){
								Method setter = properdesc.getWriteMethod();
                                    //获取属性的setter方法 ,private
								if(setter!=null){
								Object value = sigletons.get(propertyDefinition.getRef());
								setter.invoke(bean, value);//把引用对象注入到属性
								}
								break;
							}
						}
					}
				} catch (Exception e) {
				}
			}
		}
	}
	/**
	 * 完成bean的实例化
	 */
	private void instanceBeans() {
		for(Definition beanDefinition : beanDefines){
			try {
				if(beanDefinition.getClassName()!=null && !"".
                                   equals(beanDefinition.getClassName().trim()))
	                          sigletons.put(beanDefinition.getId(), 
                                  Class.forName(beanDefinition.getClassName()).newInstance());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
	}
	/**
	 * 读取xml配置文件
	 * @param filename
	 */
	private void readXML(String filename) {
	       SAXReader saxReader = new SAXReader();   
	        Document document=null;   
	        try{
	         URL xmlpath = this.getClass().getClassLoader().getResource(filename);
	         document = saxReader.read(xmlpath);
	         Map<String,String> nsMap = new HashMap<String,String>();
	         nsMap.put("ns","http://www.springframework.org/schema/beans");//加入命名空间
                 //创建beans/bean查询路径      
                XPath xsub = document.createXPath("//ns:beans/ns:bean");
	         xsub.setNamespaceURIs(nsMap);//设置命名空间
	         List<Element> beans = xsub.selectNodes(document);//获取文档下所有bean节点 
	         for(Element element: beans){
	            String id = element.attributeValue("id");//获取id属性值
	            String clazz = element.attributeValue("class"); //获取class属性值        
	            BeanDefinition beanDefine = new BeanDefinition(id, clazz);
	            XPath propertysub =  element.createXPath("ns:property");
	            propertysub.setNamespaceURIs(nsMap);//设置命名空间
	            List<Element> propertys = propertysub.selectNodes(element);
	            for(Element property : propertys){	            	
                        //元素内部引用的属性也获取
	            	String propertyName = property.attributeValue("name");
	            	String propertyref = property.attributeValue("ref");
	            	ProsDefinition propertyDefinition = 
                         new ProsDefinition(propertyName, propertyref);
	            	beanDefine.getPropertys().add(propertyDefinition);
	            }
	            beanDefines.add(beanDefine);
	         } 
	        }catch(Exception e){   
	            e.printStackTrace();
	        }
	}
	/**
	 * 获取bean实例
	 * @param beanName
	 * @return
	 */
	public Object getBean(String beanName){
		return this.sigletons.get(beanName);
	}
}

 

上面简单的依赖注入 基本完成 当然spring的源码会管家复杂  我们主要是理解其思想  下面我们来测试

 

Java代码 复制代码  收藏代码
  1. public class SpringTest {   
  2.   
  3.     @BeforeClass  
  4.     public static void setUpBeforeClass() throws Exception {   
  5.     }   
  6.   
  7.     @Test public void instanceSpring(){   
  8.         LeamClassPathXMLApplicationContext ctx = new  
  9.                                       LeamClassPathXMLApplicationContext("beans.xml");   
  10.         PersonService personService = (PersonService)ctx.getBean("personService");   
  11.         personService.save();          
  12.     }   
  13. }  
public class SpringTest {

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
	}

	@Test public void instanceSpring(){
		LeamClassPathXMLApplicationContext ctx = new
                                      LeamClassPathXMLApplicationContext("beans.xml");
		PersonService personService = (PersonService)ctx.getBean("personService");
		personService.save();		
	}
}

 

 

 

最终输出 说明实例化成功

 

执行add()方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值