轉: Spring的自動裝配 autowire

來源:互聯網
上載者:User

 http://tjc.javaeye.com/blog/341430

 

 

 

今天來整理一下Spring的自動裝配 autowire一節,在這裡我們要解決以下問題: 
§1 什麼是自動裝配? 
§2 自動裝配的意義? 
§3 自動裝配有幾種類型? 
§4 如何啟用自動裝配? 
§5 自動裝配將引發的問題? 

§1 什麼是自動裝配? 
Spring reference 寫道 The  Spring container is able to  autowire relationships between collaborating beans. This means that it is 
possible to automatically let  Spring resolve collaborators (other beans) for your bean by inspecting the contents 
of the BeanFactory.
引用 Spring IoC容器可以自動裝配( autowire)相互協作bean之間的關聯關係。因此,如果可能的話,可以自動讓 Spring通過檢查BeanFactory中的內容,來替我們指定bean的共同作業者(其他被依賴的bean)。
簡而言之,就是對於bean當中引用的其他bean不需要我們自己去配置它改使用哪個類, Spring 的自動裝配可以協助我們完成這些工作。 

§2 自動裝配的意義? 
Spring reference 寫道 It is important to understand the various advantages and disadvantages of autowiring. Some advantages of 
autowiring include: 
• Autowiring can significantly reduce the volume of configuration required. However, mechanisms such as the 
use of a bean template (discussed elsewhere in this chapter) are also valuable in this regard. 
• Autowiring can cause configuration to keep itself up to date as your objects evolve. For example, if you need 
to add an additional dependency to a class, that dependency can be satisfied automatically without the need 
to modify configuration. Thus there may be a strong case for autowiring during development, without ruling 
out the option of switching to explicit wiring when the code base becomes more stable.
引用 理解自動裝配的優缺點是很重要的。其中優點包括: 

自動裝配能 顯著減少配置的數量。不過,採用bean模板(見這裡)也可以達到同樣的目的。 

自動裝配可以使配置與java代碼同步更新。例如,如果你需要給一個java類 增加一個依賴,那麼該 依賴將被自動實現而不需要修改配置。因此強烈推薦在開發過程中採用自動裝配,而在系統趨於穩定的時候改為顯式裝配的方式。 

§3 自動裝配有幾種類型? 
Spring reference 寫道
Mode                               Explanation 
no             No autowiring at all. Bean references must be defined via a ref   element. This is the  default, 
                and changing this is discouraged for larger deployments, since explicitly specifying collaborators gives 
                greater control and clarity. To some extent, it is a form of documentation about the structure of a system. 

byName       Autowiring by property name. This option will inspect the container and look for a bean named exactly 
                the same as the property which needs to be autowired. For example, if you have a bean definition which is 
                set to  autowire by name, and it contains a master property(that is, it has a setMaster(..) method),  Spring 
                will look for a bean definition named master, and use it to set the property. 

byType       Allows a property to be autowired if there is exactly one bean of the property type in the 
               container. If there is more than one, a fatal exception is thrown, and this indicates that you 
               may not use byType autowiring for that bean. If there are no matching beans, nothing 
               happens; the property is not set. If this is not desirable, setting the dependency-check="objects" 
               attribute value specifies that an error should be thrown in this case.  

constructor    This is analogous to byType, but applies to constructor arguments. If there isn't exactly one 
                bean of the constructor argument type in the container, a fatal error is raised. 

autodetect     Chooses constructor or byType through introspection of the bean class. If a default 
                constructor is found, the byType mode will be applied. 
引用
模式                  說明 
no            預設不使用autowiring。 必須顯示的使用"<ref />"標籤明確地指定bean合作者,對於部署給予更大的 
                控制和明了。 

byName       根據屬性名稱自動裝配。此選項將檢查容器並根據名字尋找與屬性完全一致的bean,並將其與屬性自 
               動裝配。例如,在bean定義中將  autowire設定為by name,而該bean包含master屬性(同時提供 
               setMaster(..)方法), Spring就會尋找名為master的bean定義,並用它來裝配給master屬性。 

byType       如果容器中存在一個與指定屬性類型相同的bean,那麼將與該屬性自動裝配。如果存在多個該類型的 
                bean,那麼將會拋出異常,並指出不能使用byType方式進行自動裝配。若沒有找到相匹配的bean, 
                則什麼事都不發生,屬性也不會被設定。如果你不希望這樣,那麼可以通過設定 
                dependency-check="objects"讓 Spring拋出異常。 

constructor   與byType的方式類似,不同之處在於它應用於構造器參數。如果在容器中沒有找到與構造器參數類 
                型一致的bean,那麼將會拋出異常。 

autodetect     通過bean類的自省機制(introspection)來決定是使用constructor還是byType方式進行自動裝配。 
                如果發現預設的構造器,那麼將使用byType方式。 


§4 如何啟用自動裝配? 
你可以參照以下的配置去啟用自動裝配 
引用 <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" 
default-autowire="byType" >
當然,這裡的byType你可以更改為其他你想要的裝配類型。 

§5 自動裝配將引發的問題? 
Spring reference 寫道
Some disadvantages of autowiring: 
• Autowiring is more magical than explicit wiring. Although, as noted in the above table,  Spring is careful to 
avoid guessing in case of ambiguity which might have unexpected results, the relationships between your 
Spring-managed objects are no longer documented explicitly. 
• Wiring information may not be available to tools that may generate documentation from a  Spring container. 
引用
自動裝配的一些缺點: 

儘管自動裝配比顯式裝配更神奇,但是,正如上面所提到的, Spring會盡量避免在裝配不明確的時候進行猜測,因為裝配不明確可能出現難以預料的結果,而且 Spring所管理的對象之間的關聯關係也不再能清晰的進行文檔化。 

對於那些根據 Spring設定檔產生文檔的工具來說,自動裝配將會使這些工具沒法產生依賴資訊。 

自動裝配可以減輕配置的工作量,但同時使得設定檔的可讀性變得很差,因為你不可能從設定檔 
中獲知這些對象之間得依賴關係,從而維護困難。 
注意: 
    當根據類型進行自動裝配的時候,容器中可能存在多個bean定義跟自動裝配的setter方法和構造器參數類型匹配。這樣就會存在模稜兩可的問題。如果bean定義不唯一,裝配時就會拋出異常。 
    解決方案(任選其一): 
    1 放棄使用自動裝配,使用顯示裝配。 
    2 將bean排除在自動裝配之外, 
        引用
           兩個功能: 
               1 通過設定bean定義中的' autowire-candidate'屬性顯式的設定為'true' 或 'false'來設定其是否為被自動裝配 
                 對象。 
               2 使用對bean名字進行模式比對來對自動裝配進行限制,其做法是在<beans/>元素的 
                 'default- autowire-candidates' 屬性中進行設定。可以使用萬用字元,如以'Repository'結尾的bean, 
                  那麼可以設定為"*Repository“。 
       
    3 通過在bean定義中設定'primary'屬性為'true'來將該bean設定為首選自動裝配bean。 
    如何使用 Spring  autowire請取決於你的項目設計。 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.