隨筆-199  評論-203  文章-11  trackbacks-0
           Spring的哲學(xué)是在不影響Java對象的設(shè)計(jì)的情況下將Java對象加入到框架中。 我們下面來看看Spring的工作原理,看看Spring是如何做到不影響Java對象的。

            EJB的框架采用了一種侵略性(Invasive)的方法來設(shè)計(jì)對象,它要求你在設(shè)計(jì)中加入符合EJB規(guī)范的代碼。一些輕量級的COP框架,例如Avalon,也要求對象設(shè)計(jì)時必須符合某種規(guī)范,例如Serviceable接口,這種做法是典型的Type 1做法。

            這種設(shè)計(jì)思路要求Spring采用一種動態(tài)的、靈活的方式來設(shè)計(jì)框架。在Spring的工作原理中大量采用了反射。首先Spring要解決的一個問題就是如何管理bean。因?yàn)镮OC的思想要求bean之間不能夠直接調(diào)用,而應(yīng)該采用一種被動的方式進(jìn)行協(xié)作。所以bean的管理是Spring工作原理中的核心部分。

            反射和內(nèi)省在代碼的層次上思考問題,有時候能夠帶來出人意料的靈活性。但它的使用有時候也是一個哲學(xué)問題,不論是在ORM設(shè)計(jì)還是在AOP設(shè)計(jì)上都出現(xiàn)了類似的問題-究竟是使用反射,還是使用代碼生成。

            在Spring中,處理這個問題的核心是在org.springframework.beans包中。而其中最為核心的部分,則是BeanWrapper。BeanWrapper,顧名思義,就是bean的包裝器。所以,它的主要工作,就是對任何一個bean,進(jìn)行屬性(包括內(nèi)嵌屬性)的設(shè)置和方法的調(diào)用。在

            BeanWrapper的默認(rèn)實(shí)現(xiàn)類BeanWrapperImpl中,雖然代碼較長,但完成的工作卻是非常的集中的。

            BeanWrapper的深入研究

            我們看看這個BeanWrapper是如何發(fā)揮運(yùn)作的,假設(shè)我們有兩個bean:

          1.    public class Company {  
          2.     private String name;  
          3.     private Employee managingDirector;  
          4.      
          5.     public String getName() {    
          6.    return this.name;    
          7.     }  
          8.     public void setName(String name) {    
          9.    this.name = name;    
          10.     }    
          11.     public Employee getManagingDirector() {    
          12.    return this.managingDirector;    
          13.     }  
          14.     public void setManagingDirector(Employee managingDirector) {  
          15.    this.managingDirector = managingDirector;    
          16.     }  
          17.    }  
          18.      
          19.    public class Employee {  
          20.     private float salary;  
          21.      
          22.     public float getSalary() {  
          23.    return salary;  
          24.     }    
          25.     public void setSalary(float salary) {  
          26.    this.salary = salary;  
          27.     }  
          28.    }  

            然后我們使用BeanWrapper來調(diào)用這兩個bean:

          1.    Company c = new Company();  
          2.    BeanWrapper bwComp = BeanWrapperImpl(c);  
          3.    // setting the company name...  
          4.    bwComp.setPropertyValue("name", "Some Company Inc.");  
          5.    // ... can also be done like this:  
          6.    PropertyValue v = new PropertyValue("name", "Some Company Inc.");  
          7.    bwComp.setPropertyValue(v);  
          8.      
          9.    // ok, lets create the director and tie it to the company:  
          10.    Employee jim = new Employee();  
          11.    BeanWrapper bwJim = BeanWrapperImpl(jim);  
          12.    bwJim.setPropertyValue("name", "Jim Stravinsky");    
          13.    bwComp.setPropertyValue("managingDirector", jim);  
          14.      
          15.    // retrieving the salary of the managingDirector through the company  
          16.    Float salary = (Float)bwComp.getPropertyValue("managingDirector.salary");  

            看起來麻煩了許多,但是這樣Spring就可以使用統(tǒng)一的方式來管理bean的屬性了。

           Bean的制造工廠

            有了對單個Bean的包裝,還需要對多個的bean進(jìn)行管理。在spring中,把bean納入到一個核心庫中進(jìn)行管理。bean的生產(chǎn)有兩種方法:一種是一個bean產(chǎn)生多個實(shí)例,一種是一個bean只產(chǎn)生一個實(shí)例。如果對設(shè)計(jì)模式熟悉的話,我們就會想到,前者可以采用Prototype,后者可以采用Singleton。

            注意到,反射技術(shù)的使用使得我們不再像原始的工廠方法模式那樣創(chuàng)建對象。反射可以非常靈活的根據(jù)類的名稱創(chuàng)建一個對象。所以spring只使用了Prototype和Singleton這兩個基本的模式。

            Spring正是這樣處理的,但是我們希望用戶能夠維護(hù)統(tǒng)一的接口,而不需要關(guān)心當(dāng)前的bean到底是Prototype產(chǎn)生的獨(dú)立的bean,還是Singleton產(chǎn)生的共享的bean。所以,在org.springframework.beans.factory包中的BeanFactory定義了統(tǒng)一的getBean方法。

            JDBC再封裝JDBC優(yōu)雅的封裝了底層的數(shù)據(jù)庫,但是JDBC仍然存在諸多的不變。你需要編寫大量的代碼來完成CRUD操作,而且,JDBC無論是遇到什么樣的問題,都拋出一個SQLException,這種做法在異常使用上被稱為不完備的信息。因?yàn)閱栴}可能是很復(fù)雜的,也許是數(shù)據(jù)庫連接的問題,也許是并發(fā)控制的問題,也許只是SQL語句出錯。沒有理由用一個簡單的SQLException就搞定全部的問題了,這種做法有些不負(fù)責(zé)任。針對這兩個問題,Spring Framework提出了兩種解決方法:首先,提供一個框架,把JDBC應(yīng)用中的獲取連接、異常處理、釋放等比較通用的操作全部都集中起來,用戶只需要提供特定的實(shí)現(xiàn)就OK了。實(shí)現(xiàn)的具體細(xì)節(jié)采用的是模板方法。舉個例子,在org.springframework.jdbc.object包中,MappingSqlQuery類實(shí)現(xiàn)了將SQL查詢映射為具體的業(yè)務(wù)對象。JavaDoc中這樣寫到:Reusable query in which concrete subclasses must implement the abstract mapRow(ResultSet, int) method to convert each row of the JDBC ResultSet into an object. 用戶必須實(shí)現(xiàn)mapRow方法,這是典型模板方法的應(yīng)用。我們拿一個具體的例子來看看:

           

          1.    class UserQuery extends MappingSqlQuery {  
          2.      
          3.     public UserQuery(DataSource datasource) {  
          4.    super(datasource, "SELECT * FROM PUB_USER_ADDRESS WHERE USER_ID = ?");  
          5.    declareParameter(new SqlParameter(Types.NUMERIC));  
          6.    compile();  
          7.     }  
          8.      
          9.     // Map a result set row to a Java object  
          10.     protected Object mapRow(ResultSet rs, int rownum) throws SQLException {  
          11.    User user = new User();  
          12.    user.setId(rs.getLong("USER_ID"));  
          13.    user.setForename(rs.getString("FORENAME"));  
          14.    return user;  
          15.     }  
          16.      
          17.     public User findUser(long id) {  
          18.    // Use superclass convenience method to provide strong typing  
          19.    return (User) findObject(id);  
          20.     }  
          21.    }

           

            其次是第二個問題,最麻煩的地方應(yīng)該說是需要截住JDBC的異常,然后判斷異常的類型,并重新拋出異常。錯誤的問題可以通過連接來獲取,所以麻煩的是如何截獲異常。Spring 框架采用的方法是回調(diào),處理回調(diào)的類在Spring Framework中被稱為template 。

           

          1.    JdbcTemplate template = new JdbcTemplate(dataSource);  
          2.    final List names = new LinkedList();  
          3.    template.query("SELECT USER.NAME FROM USER",  
          4.    new RowCallbackHandler() {  
          5.     public void processRow(ResultSet rs) throws SQLException {  
          6.    names.add(rs.getString(1));  
          7.     }  
          8.    });

           

            回調(diào)函數(shù)是一個匿名類,其中也使用了模板方法,異常的處理都在父類中完成了

            層間松耦合

            在開放源碼界已經(jīng)出現(xiàn)了大量的基于MVC的Web容器,但是這些容器都僅限于Web的范圍 ,不涉及Web層次后端的連接,Spring作為一個整體性的框架,定義了一種Web層和后端業(yè)務(wù)層的連接方式, 這個思路仍然疏運(yùn)圖MVC的范疇,但耦合更松散,不依賴于具體的集成層次。

           

          1.    public class GoogleSearchController  
          2.    implements Controller {  
          3.      
          4.     private IGoogleSearchPort google;  
          5.      
          6.     private String googleKey;  
          7.      
          8.     public void setGoogle(IGoogleSearchPort google) {  
          9.    this.google = google;  
          10.     }  
          11.      
          12.     public void setGoogleKey(String googleKey) {  
          13.    this.googleKey = googleKey;  
          14.     }  
          15.      
          16.     public ModelAndView handleRequest(  
          17.    HttpServletRequest request, HttpServletResponse response)  
          18.    throws ServletException, IOException {  
          19.     String query = request.getParameter("query");  
          20.     GoogleSearchResult result =  
          21.     // Google property definitions omitted...  
          22.      
          23.     // Use google business object  
          24.     google.doGoogleSearch(this.googleKey, query,start, maxResults, filter, r  
          25.    estrict, safeSearch, lr, ie, oe);  
          26.      
          27.     return new ModelAndView("googleResults", "result", result);  
          28.    }  
          29.     }  

           

            回調(diào)函數(shù)是一個匿名類,其中也使用了模板方法,異常的處理都在父類中完成了。

          posted on 2009-07-02 17:34 Werther 閱讀(1837) 評論(2)  編輯  收藏 所屬分類: 22.Spring

          評論:
          # re: Spring工作原理探秘 2009-07-03 01:02 | IceRao
          不錯的文章。

          但是標(biāo)題顯然不夠恰當(dāng),文章并沒有講太多原理性的東西。  回復(fù)  更多評論
            
          # re: Spring工作原理探秘 2009-07-03 07:51 | Werther
          @IceRao
          Well, have you got any other suggestions then? IceRao
            回復(fù)  更多評論
            

          只有注冊用戶登錄后才能發(fā)表評論。


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 建阳市| 城口县| 丽江市| 巴林右旗| 高密市| 开鲁县| 阿克陶县| 崇义县| 通道| 永济市| 德惠市| 太湖县| 营山县| 衡阳市| 吉木乃县| 于田县| 托里县| 隆昌县| 揭阳市| 海安县| 舟山市| 通化市| 平安县| 临潭县| 鱼台县| 红安县| 内丘县| 林芝县| 三门县| 巧家县| 襄垣县| 望谟县| 安泽县| 翁源县| 化德县| 广丰县| 英德市| 长白| 渭源县| 丰台区| 阳曲县|