Spring框架---溫習(xí)(轉(zhuǎn))

          Spring是什么?
             Spring是一個(gè)開(kāi)源的控制反轉(zhuǎn)(Inversion of Control,IoC)和面向切面(AOP)的容器框架,它的主要目的是簡(jiǎn)化企業(yè)開(kāi)發(fā)。
          IOC 控制反轉(zhuǎn)
             先看一下一段代碼

          public class PersonServiceBean{
             private PersonDao personDao = new PersonDaoBean();
             public void save(Person person){
                personDao.save(person);
             }
          }

          PersonDaoBean是在應(yīng)用內(nèi)部(PersonServiceBean)創(chuàng)建及維護(hù)的。所以控制反轉(zhuǎn)就是應(yīng)用本身不負(fù)責(zé)依賴對(duì)象的創(chuàng)建及維護(hù)。依賴對(duì)象的創(chuàng)建及維護(hù)是由外部容器負(fù)責(zé)的。這樣控制權(quán)就由應(yīng)用轉(zhuǎn)移到了外部容器,控制權(quán)的轉(zhuǎn)移就是所謂反轉(zhuǎn)。
          依賴注入(Dependency Injection)
          當(dāng)我們把依賴對(duì)象交給外部容器負(fù)責(zé)創(chuàng)建,那么PersonServiceBean類可以改成如下:

          public class PersonServiceBean{
               private PersonDao personDao;
             //通過(guò)構(gòu)造器參數(shù),讓容器把創(chuàng)建好的依賴對(duì)象注入進(jìn)PersonServiceBean,當(dāng)然也可以使用setter方法進(jìn)行注入。
               public PersonServiceBean(PersonDao personDao){
                   this.personDao = personDao ;
            }
              public void save(Person person){
                  personDao.save(person);
            }
          }

          所謂依賴注入就是指:在運(yùn)行期,由外部容器動(dòng)態(tài)地將依賴對(duì)象注入到組件中。
          為什么要使用Spring?
             1.降低組件之間的耦合度,實(shí)現(xiàn)軟件各層之間的解耦。
                          Controller ——》Service ——》 DAO
             2.可以使用容器提供的眾多服務(wù),如事務(wù)管理服務(wù)、消息服務(wù)等。當(dāng)我們使用容器管理事務(wù)時(shí),開(kāi)發(fā)人員就不再需要手工控制事務(wù),也不需處理復(fù)雜的事物傳播。
                 
           


             3.容器提供單例模式支持。開(kāi)發(fā)人員不再需要自己填寫(xiě)實(shí)現(xiàn)代碼。
             4.容器提供了AOP技術(shù),利用它很容易實(shí)現(xiàn)如權(quán)限攔截、運(yùn)行期監(jiān)控等功能。
             5.容器提供的眾多輔助類,使用這些類能夠加快應(yīng)用的開(kāi)發(fā),如JDBC Template、Hibernate Template。
             6.Spring對(duì)于主流的應(yīng)用框架提供了集成支持,如集成Hibernate、JPA、Struts等,這樣更便于應(yīng)用的開(kāi)發(fā)。

          搭建與測(cè)試Spring的開(kāi)發(fā)環(huán)境
           使用版本為Spring2.5.6

          新建一個(gè)Java Project 命名為spring 并導(dǎo)入相關(guān)的jar包
          配置Spring配置文件

          在src下新建beans.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"
                 xsi:schemaLocation="http://www.springframework.org/schema/beans
                     http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
          </beans>


          實(shí)例化Spring容器 建議用方法一

          新建一個(gè)單元測(cè)試SpringTest,并導(dǎo)入測(cè)試所用的包

          package junit.test;
          import org.junit.BeforeClass;
          import org.junit.Test;
          import org.springframework.context.ApplicationContext;
          import org.springframework.context.support.ClassPathXmlApplicationContext;
          import cn.itcast.service.PersonService;

          public class SpringTest {
              @BeforeClass
              public static void setUpBeforeClass() throws Exception {
              }
              @Test public void instanceSpring(){
                  ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
                      }
          }


          新建一個(gè)業(yè)務(wù)Bean,命名為PersonServiceBean;抽取PersonServiceBean的接口。

          package cn.itcast.service.impl;

          import cn.itcast.service.PersonService;
          public class PersonServiceBean implements PersonService {

              public void save(){
                  System.out.println("我是save()方法");
              }
          }

          package cn.itcast.service;

          public interface PersonService {

              public void save();

          }

          在配置文件中加入如下語(yǔ)句實(shí)現(xiàn)
          <bean id="personService" class="cn.itcast.service.impl.PersonServiceBean"></bean>
          注意:編寫(xiě)spring配置文件時(shí),不能出現(xiàn)幫助信息 同通過(guò)如下方法解決


          修改SpringTest代碼 

          package junit.test;
          import org.junit.BeforeClass;
          import org.junit.Test;
          import org.springframework.context.ApplicationContext;
          import org.springframework.context.support.ClassPathXmlApplicationContext;
          import cn.itcast.service.PersonService;

          public class SpringTest {

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

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

          在實(shí)例化了容器之后,從容器中取得bean,再調(diào)用業(yè)務(wù)bean的save方法

          執(zhí)行SpringTest文件 觀察控制臺(tái)輸出



          以上證明本Spring程序運(yùn)行成功!

          編碼剖析Spring管理Bean的原理

          通過(guò)第一個(gè)實(shí)例我們會(huì)有一個(gè)疑問(wèn),Spring到底是怎么管理Bean的呢?
          我們來(lái)模擬Spring的內(nèi)部實(shí)現(xiàn)
          在junit.test下新建ItcastClassPathXMLApplicationContext類

          類的完全代碼(這里要引入dom4j的jar包)

          package junit.test;

          import java.net.URL;
          import java.util.ArrayList;
          import java.util.HashMap;
          import java.util.HashSet;
          import java.util.List;
          import java.util.Map;

          import org.dom4j.Document;
          import org.dom4j.Element;
          import org.dom4j.XPath;
          import org.dom4j.io.SAXReader;

          /**
           
          * 傳智傳客版容器
           
          *
           
          */
          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();
              }
              /**
               * 完成bean的實(shí)例化
               */
              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);
                       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");//創(chuàng)建beans/bean查詢路徑
                       xsub.setNamespaceURIs(nsMap);//設(shè)置命名空間
                       List<Element> beans = xsub.selectNodes(document);//獲取文檔下所有bean節(jié)點(diǎn) 
                       for(Element element: beans){
                          String id = element.attributeValue("id");//獲取id屬性值
                          String clazz = element.attributeValue("class"); //獲取class屬性值        
                          BeanDefinition beanDefine = new BeanDefinition(id, clazz);
                          beanDefines.add(beanDefine);
                       }   
                      }catch(Exception e){   
                          e.printStackTrace();
                      }
              }
              /**
               * 獲取bean實(shí)例
               * @param beanName
               * @return
               */
              public Object getBean(String beanName){
                  return this.sigletons.get(beanName);
              }
          }


          新建BeanDefinition ,用來(lái)存放bean里面的兩個(gè)屬性 id 和 className。

          package junit.test;

          public class BeanDefinition {
              private String id;
              private String className;
             
              public BeanDefinition(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;
              }
             
          }


          修改SpringTest代碼 測(cè)試程序

          package junit.test;
          import org.junit.BeforeClass;
          import org.junit.Test;
          import cn.itcast.service.PersonService;

          public class SpringTest {

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

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


          執(zhí)行測(cè)試 控制臺(tái)輸出為


          說(shuō)明我們新建的傳智播客容器取到了bean實(shí)例 并成功地調(diào)用了save方法
          通過(guò)實(shí)例,我們就可以理解Spring是創(chuàng)建和管理bean的!

          posted on 2009-05-08 13:22 彭偉 閱讀(288) 評(píng)論(0)  編輯  收藏 所屬分類: 框架技術(shù)分區(qū)

          <2009年5月>
          262728293012
          3456789
          10111213141516
          17181920212223
          24252627282930
          31123456

          導(dǎo)航

          統(tǒng)計(jì)

          常用鏈接

          留言簿(3)

          隨筆分類

          隨筆檔案

          搜索

          最新評(píng)論

          閱讀排行榜

          評(píng)論排行榜

          主站蜘蛛池模板: 凭祥市| 溆浦县| 吴旗县| 宜黄县| 万宁市| 奉节县| 徐州市| 博客| 义乌市| 禄丰县| 迭部县| 社会| 天水市| 方山县| 永春县| 宜黄县| 辽宁省| 衢州市| 翼城县| 高清| 洛南县| 九龙坡区| 梁山县| 新余市| 西宁市| 三亚市| 宁城县| 呈贡县| 哈尔滨市| 高邑县| 阳信县| 阿拉善盟| 疏附县| 峡江县| 桂平市| 澎湖县| 英山县| 乌鲁木齐市| 武清区| 承德市| 华池县|