Spring框架源码学习---DI的实现

依赖注入:

 this.readXML(filename);

List<BeanDefinition> beanDefines = new ArrayList<BeanDefinition>();

BeanDefinition中有PropertyDefinition

this.instanceBeans();

先实例化每个Bean,但并不注入值,通过反射实现的。然后以id为键存入singleton Map中。

this.injectObject();

遍历所有的bean,从上面map中得到bean实例,然后通过内省看看这个bean实例有哪些属性需要注入,如果有的话,再将其和beanDefines中的比较,从singleton中取出,然后通过内省的方式调用setter方法注入即可。

 

 

public class ItcastClassPathXMLApplicationContext {
 private List<BeanDefinition> beanDefines = new ArrayList<BeanDefinition>();
 private Map<String, Object> sigletons = new HashMap<String, Object>();
 
 public ItcastClassPathXMLApplicationContext(String filename){
  this.readXML(filename);
  this.instanceBeans();
  this.injectObject();//注入对象
 }
 /**
  * bean对象属性注入值 
  */
 private void injectObject() {
   for(BeanDefinition beanDefinition:beanDefines){//循环所有的bean
    Object bean=sigletons.get(beanDefinition.getId());//通过Id取得实例化后beanDefines中的Bean
    if(bean!=null){//判断bean是否获取到
     try {
     PropertyDescriptor[] ps=Introspector.getBeanInfo(bean.getClass()).getPropertyDescriptors();// 取得bean的属性描述
     for(PropertyDefinition propertyDefinition:beanDefinition.getPropertys()){
       for(PropertyDescriptor properdesc:ps){
        if(propertyDefinition.getName().equals(properdesc.getName())){//判断循环的属性是否在bean中存在
         Method setter=properdesc.getWriteMethod();//获取属性的setter方法
         if(setter!=null){//判断属性是否有setter方法
          Object value=sigletons.get(propertyDefinition.getRef());//取得ref所引用的对象
          setter.setAccessible(true);//设置为允许访问,防止setter方法为私有时抛出异常
          setter.invoke(bean, value);//把引用对象注入到属性中
         }
         break;
        }
       }
      }
    } catch (Exception e) {
     e.printStackTrace();
    }
    }
   }
 }
 /**
  * 完成bean的实例化
  */
 private void instanceBeans() {
  for(BeanDefinition 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);//读取文件的内容得到一个document
          Map<String,String> nsMap = new HashMap<String,String>();
          nsMap.put("ns","http://www.springframework.org/schema/beans");//加入命名空间
          XPath xsub = document.createXPath("//ns:beans/ns:bean");//创建beans/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");//通过element创建查询路径,此时的路径为相对路径(即://ns:beans/ns:bean下的ns:property
             propertysub.setNamespaceURIs(nsMap);//设置命名空间 
             List<Element> propertys=propertysub.selectNodes(element);//获取文档下所有bean节点 
             for(Element property:propertys){
              String propertyName=property.attributeValue("name");//获取属性的nameref
              String propertyref=property.attributeValue("ref");
//              System.out.println(propertyName+"="+propertyref);
              PropertyDefinition propertyDefinition=new PropertyDefinition(propertyName,propertyref);//nameref赋给propertyDefinition
              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);
 }
}

--------------------------------------------------------------------------------------------------

<?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.itcast.dao.impl.PersonDaoBean"></bean>
       <bean id="personService" class="cn.itcast.service.impl.PersonServiceBean">
         <property name="personDao" ref="personDao"></property>
         <property name="name" value="itcast"></property>
           <property name="id" value="88"></property>
       </bean>
</beans>
-----------------------------------------------------------------------------------------------------------------
public class PersonServiceBean implements PersonService {
 private PersonDao personDao;
 private String name;
 private int id;
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public PersonDao getPersonDao() {
  return personDao;
 }
 public void setPersonDao(PersonDao personDao) {
  this.personDao = personDao;
 }
 @Override
 public void save(){
  System.out.println("id="+id+"\tname="+name);
  personDao.add();
 }
}
-----------------------------------------------------------
public class ItcastClassPathXMLApplicationContext {
 private List<BeanDefinition> beanDefines = new ArrayList<BeanDefinition>();
 private Map<String, Object> sigletons = new HashMap<String, Object>();

 

 public ItcastClassPathXMLApplicationContext(String filename) {
  this.readXML(filename);
  this.instanceBeans();
  this.injectObject();// 注入对象
 }

 

 /**
  * bean对象属性注入值
  */
 private void injectObject() {
  for (BeanDefinition beanDefinition : beanDefines) {// 循环所有的bean
   Object bean = sigletons.get(beanDefinition.getId());// 通过Id取得实例化后beanDefines中的Bean
   if (bean != null) {// 判断bean是否获取到
    try {
     PropertyDescriptor[] ps = Introspector.getBeanInfo(bean.getClass()).getPropertyDescriptors();// 取得bean的属性描述
     for (PropertyDefinition propertyDefinition : beanDefinition.getPropertys()) {
      for (PropertyDescriptor properdesc : ps) {
       if (propertyDefinition.getName().equals(properdesc.getName())) {// 判断循环的属性是否在bean中存在
        Method setter = properdesc.getWriteMethod();// 获取属性的setter方法
        if (setter != null) {// 判断属性是否有setter方法
         Object value = null;
         if(propertyDefinition.getRef()!=null && !"".equals(propertyDefinition.getRef().trim())){// 如果引用存在
          value = sigletons.get(propertyDefinition.getRef());// 取得ref所引用的对象
         } else {
          // 通过ConvertUtilspropertyDefinition.getValue()转换成与properdesc.getPropertyType()对应的值
          value = ConvertUtils.convert(propertyDefinition.getValue(), properdesc.getPropertyType());
         }
         setter.setAccessible(true);// 设置为允许访问,防止setter方法为私有时抛出异常
         setter.invoke(bean, value);// 把引用对象注入到属性中
        }
        break;
       }
      }
     }
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  }
 }

 

 /**
  * 完成bean的实例化
  */
 private void instanceBeans() {
  for (BeanDefinition 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);// 读取文件的内容得到一个document
   Map<String, String> nsMap = new HashMap<String, String>();
   nsMap.put("ns", "http://www.springframework.org/schema/beans");// 加入命名空间
   XPath xsub = document.createXPath("//ns:beans/ns:bean");// 创建beans/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");// 通过element创建查询路径,此时的路径为相对路径(即://ns:beans/ns:bean下的ns:property
    propertysub.setNamespaceURIs(nsMap);// 设置命名空间
    List<Element> propertys = propertysub.selectNodes(element);// 获取文档下所有bean节点
    for (Element property : propertys) {
     String propertyName = property.attributeValue("name");// 获取属性的nameref
     String propertyref = property.attributeValue("ref");
     String propertyValue = property.attributeValue("value");
     // System.out.println(propertyName+"="+propertyref);
     PropertyDefinition propertyDefinition = new PropertyDefinition(propertyName, propertyref, propertyValue);// nameref赋给propertyDefinition
     beanDefine.getPropertys().add(propertyDefinition);
    }
    beanDefines.add(beanDefine);
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
 }


参考:http://www.cnblogs.com/mingforyou/archive/2011/12/20/2294925.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值