Spring自動裝配Beans

在Spring框架,可以用 auto-wiring 功能會自動裝配Bean。要啟用它,只需要在 <bean>定義“autowire”屬性。

<bean id="customer" class="com.yiibai.common.Customer" autowire="byName" />
在Spring中,支持 5 自動裝配模式。
no – 缺省情況下,自動配置是通過“ref”屬性手動設(shè)定
byName – 根據(jù)屬性名稱自動裝配。如果一個(gè)bean的名稱和其他bean屬性的名稱是一樣的,將會自裝配它。
byType – 按數(shù)據(jù)類型自動裝配。如果一個(gè)bean的數(shù)據(jù)類型是用其它bean屬性的數(shù)據(jù)類型,兼容并自動裝配它。
constructor – 在構(gòu)造函數(shù)參數(shù)的byType方式。
autodetect – 如果找到默認(rèn)的構(gòu)造函數(shù),使用“自動裝配用構(gòu)造”; 否則,使用“按類型自動裝配”。

示例
Customer 和 Person 對象自動裝配示范。
package com.yiibai.common;public class Customer { private Person person; public Customer(Person person) { this.person = person; } public void setPerson(Person person) { this.person = person; } //...}
package com.yiibai.common;public class Person { //...}

  1. Auto-Wiring ‘no’
    這是默認(rèn)的模式,你需要通過 'ref' 屬性來連接 bean。
    <bean id="customer" class="com.yiibai.common.Customer"> <property name="person" ref="person" /> </bean> <bean id="person" class="com.yiibai.common.Person" />
  2. Auto-Wiring ‘byName’
    按屬性名稱自動裝配。在這種情況下,由于對“person” bean的名稱是相同于“customer” bean 的屬性(“person”)名稱,所以,Spring會自動通過setter方法將其裝配 – “setPerson(Person person)“.
    <bean id="customer" class="com.yiibai.common.Customer" autowire="byName" /> <bean id="person" class="com.yiibai.common.Person" />
    查看完整的示例 – Spring按名稱自動裝配
  3. Auto-Wiring ‘byType’
    通過按屬性的數(shù)據(jù)類型自動裝配Bean。在這種情況下,由于“Person” bean中的數(shù)據(jù)類型是與“customer” bean的屬性(Person對象)的數(shù)據(jù)類型一樣的,所以,Spring會自動通過setter方法將其自動裝配。– “setPerson(Person person)“.
    <bean id="customer" class="com.yiibai.common.Customer" autowire="byType" /><bean id="person" class="com.yiibai.common.Person" />
    查看完整的示例 – Spring通過類型自動裝配
  4. Auto-Wiring ‘constructor’
    通過構(gòu)造函數(shù)參數(shù)的數(shù)據(jù)類型按屬性自動裝配Bean。在這種情況下,由于“person” bean的數(shù)據(jù)類型與“customer” bean的屬性(Person對象)的構(gòu)造函數(shù)參數(shù)的數(shù)據(jù)類型是一樣的,所以,Spring通過構(gòu)造方法自動裝配 – “public Customer(Person person)“.
    <bean id="customer" class="com.yiibai.common.Customer" autowire="constructor" /> <bean id="person" class="com.yiibai.common.Person" />
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,569評論 19 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,275評論 6 342
  • 文章作者:Tyan博客:noahsnail.com 3.4 依賴 標(biāo)準(zhǔn)企業(yè)應(yīng)用不會由一個(gè)對象(或Spring用語中...
    SnailTyan閱讀 1,266評論 0 1
  • 文章作者:Tyan博客:noahsnail.com 3.4 Dependencies A typical ente...
    SnailTyan閱讀 4,493評論 2 7
  • 夢是創(chuàng)意的源泉,心靈是創(chuàng)意的加工廠,在噩中找到悅的故事,是思想、思維的再造和鍛煉,觸摸自己的思維軌跡,并進(jìn)行...
    紫雨true閱讀 262評論 0 1

友情鏈接更多精彩內(nèi)容