當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring自动装配Beans
生活随笔
收集整理的這篇文章主要介紹了
Spring自动装配Beans
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在Spring框架,可以用?auto-wiring?功能會自動裝配Bean。要啟用它,只需要在?<bean>定義“autowire”屬性。 <bean id="customer" class="com.yiibai.common.Customer" autowire="byName" />
在Spring中,支持?5?自動裝配模式。
- no –?缺省情況下,自動配置是通過“ref”屬性手動設定
- byName –?根據屬性名稱自動裝配。如果一個bean的名稱和其他bean屬性的名稱是一樣的,將會自裝配它。
- byType –?按數據類型自動裝配。如果一個bean的數據類型是用其它bean屬性的數據類型,兼容并自動裝配它。
- constructor –?在構造函數參數的byType方式。
- autodetect –?如果找到默認的構造函數,使用“自動裝配用構造”;?否則,使用“按類型自動裝配”。
示例
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’
這是默認的模式,你需要通過?'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’
通過按屬性的數據類型自動裝配Bean。在這種情況下,由于“Person”?bean中的數據類型是與“customer”?bean的屬性(Person對象)的數據類型一樣的,所以,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’
通過構造函數參數的數據類型按屬性自動裝配Bean。在這種情況下,由于“person”?bean的數據類型與“customer”?bean的屬性(Person對象)的構造函數參數的數據類型是一樣的,所以,Spring通過構造方法自動裝配?– “public Customer(Person person)“.
<bean id="customer" class="com.yiibai.common.Customer" autowire="constructor" /><bean id="person" class="com.yiibai.common.Person" />查看完整的示例?–?
查看完整的示例?–?Spring按AutoDetect自動裝配成功.
注 這是一件好事,這兩個auto-wire’?和?‘dependency-check’?相結合,以確保屬性始終自動裝配成功。 <bean id="customer" class="com.yiibai.common.Customer" autowire="autodetect" dependency-check="objects /><bean id="person" class="com.yiibai.common.Person" />結論
在我看來,Spring?‘auto-wiring’?以極大的成本做出更快開發效率?-?它增加了對整個?bean?配置文件復雜性,甚至不知道哪些bean將自動裝配哪個Bean。在實踐中,我更頃向手動關聯創建,它始終是干凈,也很好地工作,或者使用?@Autowired?注解,這是更加靈活和建議。
總結
以上是生活随笔為你收集整理的Spring自动装配Beans的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 老万空气能kD一90N1&#47
- 下一篇: 118平方装修技巧有哪些