日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

Spring自动装配Beans

發布時間:2024/9/20 javascript 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。