zoukankan      html  css  js  c++  java
  • 注入依赖对象

     注入依赖对象
     基本类型对象注入:
     <bean id="orderService" class="cn.itcast.service.OrderserviceBean">
     <constructor-arg index="0" type="java.lang.String" value="xxx"/>//构造器注入
     <property name="name" value="zhao"/>//属性setter方法注入
    </bean>
    注入其他bean:
    方式一:
    <bean id="orderDao" class="cn.itcast.service.OrderDaoBean"/>
    <bean id="orderService" class="cn.itcast.service.OrderServiceBean"/>
     <property name="OrderDao" ref="orderDao"/>
    </bean>
    方式二(使用内部bean,但该bean不能被其他bean使用)
    <bean id="orderService" class="cn.itcast.service.OrderServiceBean">
     <property name="orderDao">
      <bean class="cn.itcast.service.OrderDaoBean"/>
     </property>
    </bean>

    <?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" default-lazy-init="false">
           <!-- default-lazy-init="false"默认(建议),设为true时对全局有效 -->   
           <!-- 用于配置要交于spring管理的bean类 ,id是为spring取的一个名称,名称是唯一的,name用于解决id对特殊字符的限制,用法与id样-->
           <!-- class为要交于spring管理的bean类 -->
           <!-- 使用类构造器实例化 -->
           <!-- init-method="init"指定在初始化时要执行的初始化方法init,destroy-method="destory"在 bean销毁前执行关闭资源的方法destory-->
           <bean id="personService1" class="cn.itcast.service.impl.PersonServiceBean" init-method="init" destroy-method="destory"></bean>
           <!-- 使用静态工厂方法实例化 -->
           <!-- lazy-init为延迟初始化,默认为false,为true时要进行延迟,在调用getBean()时初始化-->
           <bean id="personService2" class="cn.itcast.service.impl.PersonServiceBeanFactory" factory-method="createPersonServiceBean" lazy-init="true"/>
           <!-- 使用实例工厂方法实例化 -->
           <bean id="personServiceFactory" class="cn.itcast.service.impl.PersonServiceBeanFactory"/>
           <bean id="personService3" factory-bean="personServiceFactory" factory-method="createPersonServiceBean2" scope="prototype"/>
           <!-- scope为Bean的作用域,默认为singleton,第一次获取时初始化,以后每次获取都是相同的这个bean。prototype,每次从容器获取bean都是新的对象 -->
           <!--方式一:-->
           <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>
           </bean><!-- --><!-- 为name属性注入值,ref要注入的bean名称(将PersonDaoBean中的add()方法注入到 PersonServiceBean中-->
           <!--方式二:采用内部bean的方式
           <bean id="personService" class="cn.itcast.service.impl.PersonServiceBean">
            <property name="personDao">
                <bean class="cn.itcast.dao.impl.PersonDaoBean"/>
               </property>
        </bean>-->
    </beans>

     IOC控制反转
    public class PersonServiceBean{
     private PersonDao personDao=new PersonDaoBean();
     public void save(Person person){
      personDao.save(person);
     }
    }

    personDaoBean是在应用内部创建及维护的。所谓控制反转就是应用本身不负责依赖对象的创建及维护,依赖对象的创建及维护是由外部容器负责的。这样控制权就由应用转移到了外部容器,控制权的转移就是所谓反转。

    依赖注入(Dependency Injection)
    当我们把依赖对象交给容器负责创建,那么PersonServiceBean类可以改成如下:
    public class PersonServiceBean{
     private PerSonDao personDao;
     //通过构造器把创建好的依赖对象注入进PersonServiceBean,当然也可以使用setter方法进行注入。
     public PersonServiceBean(PersonDao personDao){
      this.personDao=personDao;
     }
     public void save(Person person){
      personDao.save(person);
     }
    }
    所谓依赖注入就是指:在运行期,由外部容器动态地将依赖对象注入到组件中。

    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");//获取属性的name和ref
                  String propertyref=property.attributeValue("ref");
    //              System.out.println(propertyName+"="+propertyref);
                  PropertyDefinition propertyDefinition=new PropertyDefinition(propertyName,propertyref);//将name和ref赋给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 {
              // 通过ConvertUtils将propertyDefinition.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");// 获取属性的name和ref
         String propertyref = property.attributeValue("ref");
         String propertyValue = property.attributeValue("value");
         // System.out.println(propertyName+"="+propertyref);
         PropertyDefinition propertyDefinition = new PropertyDefinition(propertyName, propertyref, propertyValue);// 将name和ref赋给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);
     }
    }
  • 相关阅读:
    print流
    java数据流
    java转换流
    爬虫(二):urllib库文件的基础和进阶(python2.7)
    爬虫实例(二):多线程,多进程对网页的爬取
    Java多线程分析 (二)---- 高并发内存模型和线程安全
    Java多线程分析 (五)---高并发线程池
    Java 多线程分析 (四) ---高并发基础知识)
    Java(生产者与消费者方法)
    Java 多线程分析 (三) --- synchronize 同步
  • 原文地址:https://www.cnblogs.com/mingforyou/p/2294925.html
Copyright © 2011-2022 走看看