千山鳥飛絕 萬徑人蹤滅
          勤練內功,不斷實踐招數。爭取早日成為武林高手
                   今天花費了半天去寫自定義容器,結果發現還是沒發實現功能,無法輸出,結果不斷的調試、測試。最后終于搞定了。原來是寫代碼的時候把讀取配置文件里方法readxml,里面讀取子屬性里面查找節點,調用查找對象搞錯了。本為propertysub.selectNodes(element),但寫為了xsub.selectNodes(element)誤用為主element里面查找子節點。還有就是在//ns:beans/ns:bean里面把冒號寫成了頓號,真是太不仔細了。

          自定義容器

          /**
           * 實現的spring容器
           *
           * @author Administrator
           *
           */
          public class ItcastClassPathXMLApplicationContext {

           private List<BeanDefinition> beanDefines = new ArrayList<BeanDefinition>();
           private Map<String, Object> sigletons = new HashMap<String, Object>();

           public ItcastClassPathXMLApplicationContext() {

           }

           public ItcastClassPathXMLApplicationContext(String filename) {
            // System.out.println("構造方法 ");
            this.readXml(filename);// 調用 讀取配置文件 的方法
            this.instanceBeans();// 調用bean的實例化
            this.injectObject();// 注入對象
           }

           /**
            * 為bean對象的屬性注入值
            */
           private void injectObject() {
            for (BeanDefinition beanDefinition : beanDefines) {
             Object bean = sigletons.get(beanDefinition.getId());
             if (bean != null) {
              // 取得屬性描述 ,是一個數組
              try {
               PropertyDescriptor[] ps = Introspector.getBeanInfo(
                 bean.getClass()).getPropertyDescriptors();
               for (PropertyDefinition 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.setAccessible(true);// 設置為可訪問
                   setter.invoke(bean, value);// 把引用對象注入到屬性
                  }
                  break;
                 }
                }
               }
              } catch (Exception e) {
               e.printStackTrace();
              }

             }
            }

           }

           /**
            * 完成bean的實例化
            */
           private void instanceBeans() {
            // System.out.println("bean實例化方法被調用");
            // 利用反射機制把bean實例化
            for (BeanDefinition beanDefinition : beanDefines) {
             try {
              // 判斷BeanDefinition的實例獲得的類名不為null和空串
              if (beanDefinition.getClassName() != null
                && !"".equals(beanDefinition.getClassName().trim()))
               sigletons.put(beanDefinition.getId(), Class.forName(
                 beanDefinition.getClassName()).newInstance());
             } catch (Exception e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
             }

            }

           }

           /**
            * 讀取配置文件信息
            *
            * @param filename
            */
           private void readXml(String filename) {
            // System.out.println("讀取xml文件的方法被調用了");

            SAXReader saxReader = new SAXReader();// 創建讀取器
            Document document = null;
            try {
             URL xmlpath = this.getClass().getClassLoader()
               .getResource(filename);//取得當前xml文件在本地的位置
             
             document = saxReader.read(xmlpath);// 讀取路徑
             System.out.println(document);
             Map<String, String> nsMap = new HashMap<String, String>();
             nsMap.put("ns", "http://www.springframework.org/schema/beans");// 加入命名空間
             XPath xsub = document.createXPath("http://ns:beans/ns:bean");// 創建beans/bean查詢路徑
             xsub.setNamespaceURIs(nsMap);// 設置命名空間
             List<Element> beans = xsub.selectNodes(document);// 獲取文檔下所有bean節點
             System.out.println(beans.size());
             for (Element element : beans) {
              String id = element.attributeValue("id");// 獲取id屬性值
              String clazz = element.attributeValue("class");// 獲取class屬性值
              BeanDefinition beanDefine = new BeanDefinition(id, clazz);
              System.out.println("id=" + id);
              System.out.println("clazz=" + 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");// 取得property的name值
               String propertyref = property.attributeValue("ref");// 取得property的ref值

               System.out.println(propertyName + "=  " + propertyref);

               PropertyDefinition propertyDefinition = new PropertyDefinition(
                 propertyName, propertyref);
               beanDefine.getPropertys().add(propertyDefinition);// 將屬性對象加入到bean中
              }

              beanDefines.add(beanDefine);
             }
            } catch (Exception e) {
             e.printStackTrace();

            }

           }

           /**
            * 獲取bean 實例
            *
            * @param beanName
            * @return
            */
           public Object getBean(String beanName) {

            
            return this.sigletons.get(beanName);
           }

          }

           bean.xml配置文件

          <?xml version="1.0" encoding="UTF-8"?>


          <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:aop="http://www.springframework.org/schema/aop"
           xmlns:tx="http://www.springframework.org/schema/tx"
           xsi:schemaLocation="
             http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
             http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
             http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"
            >
           <bean id="personService"
            class="cn.itcast.service.impl.PersonServiceBean">
            <property name="IPersonDao" ref="personDaoBean"></property>
            
            </bean>
            <bean id="personDaoBean" class="cn.itcast.dao.impl.PersonDaoBean"></bean>  
          </beans>


          自定義屬性類 PropertyDefinition.java

          package junit.test;

          public class PropertyDefinition {
           private String name;
           private String ref;
           public PropertyDefinition(String name, String ref) {
            
            this.name = name;
            this.ref = ref;
           }
            getter&setter method

          }


          測試類:springTest


          package junit.test;

          import org.junit.BeforeClass;
          import org.junit.Test;
          import org.springframework.context.ApplicationContext;
          import org.springframework.context.support.AbstractApplicationContext;
          import org.springframework.context.support.ClassPathXmlApplicationContext;
          import org.springframework.context.support.FileSystemXmlApplicationContext;

          import cn.itcast.service.IPersonService;
          import cn.itcast.service.impl.PersonServiceBean;

          public class SpringTest {

           @BeforeClass
           public static void setUpBeforeClass() throws Exception {

           }
           @Test
           public void instanceSpring() {
          //  ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
          //    "beans.xml");
            ItcastClassPathXMLApplicationContext ctx=new ItcastClassPathXMLApplicationContext("beans.xml");
            
            IPersonService ipersonService = (IPersonService)ctx
              .getBean("personService");//調用自定義容器的getBean方法
            ipersonService.Save();
          //  ctx.close();
            // ctx.registerShutdownHook();

           }
          }

          自定義bean類:

          package junit.test;

          import java.util.ArrayList;
          import java.util.List;

          public class BeanDefinition {
           
           private String id;
           private String className;
           private List<PropertyDefinition> propertys=new ArrayList<PropertyDefinition>();
           生成getter,setter方法
           }



          package cn.itcast.dao.impl;

          import cn.itcast.dao.IPersonDao;

          public class PersonDaoBean implements IPersonDao {
           public void add(){
            System.out.println("這是personDaoBean的Add()方法");
           }
          }




          package cn.itcast.service;

          public interface IPersonService {

           public abstract void Save();

          }




          package cn.itcast.service.impl;


          import cn.itcast.dao.IPersonDao;
          import cn.itcast.service.IPersonService;
          /**
           * 業務bean
           * @author Administrator
           *
           */
          public class PersonServiceBean implements IPersonService {

           private IPersonDao iPersonDao;
           
           public IPersonDao getIPersonDao() {
            return iPersonDao;
           }

           public void setIPersonDao(IPersonDao personDao) {
            iPersonDao = personDao;
           }

           public void Save(){
            iPersonDao.add();
           }
           
           
          }



          運行測試類
          out:
           這是personDaoBean的Add()方法


          posted on 2009-08-27 14:46 笑口常開、財源滾滾來! 閱讀(154) 評論(0)  編輯  收藏 所屬分類: spring學習
           
          主站蜘蛛池模板: 无为县| 锡林郭勒盟| 茂名市| 湘阴县| 定南县| 吴江市| 南皮县| 萝北县| 土默特右旗| 顺平县| 马龙县| 乌什县| 临海市| 青州市| 张掖市| 霍州市| 茶陵县| 临邑县| 南丰县| 周口市| 平江县| 正蓝旗| 房产| 竹北市| 广西| 高清| 南充市| 岑溪市| 清丰县| 连城县| 万荣县| 拉孜县| 乐平市| 旬邑县| 通化市| 阳山县| 宁河县| 河曲县| 托克托县| 长兴县| 宜川县|