【spring教程之八】spring自動裝配,spring教程裝配

來源:互聯網
上載者:User

【spring教程之八】spring自動裝配,spring教程裝配

1、在我們之間的spring裝配中,如果一個bean用到了另外一個bean檔案,那麼格式應該是這樣的:

<!-- 主bean --><bean id="A" class="com.test.pro.Singer"><property name="myb" ref="B"></property></bean><!-- 被裝配的bean --><bean id="B" class="com.test.pro.Instrument"></bean>

即beanA需要使用存取器注入B的時候,就需要上面的配置。

但是在自動裝配中,假如在beanA中的屬性值myb和B中的id一樣的時候,就可以預設注入,不用顯示的設定,即只要使用下面的格式就好:

<!-- 主bean --><bean id="A" class="com.test.pro.Singer"><!-- <property name="myb" ref="B"></property> 這句話可以省略掉--></bean><!-- 被裝配的bean --><bean id="myb" class="com.test.pro.Instrument"></bean>

2、核心xml設定檔

 <bean id="piano" class="com.test.pro.Instrument">      <property name="name" value="鋼琴"></property></bean> <bean id="jack" class="com.test.pro.Singer" autowire="byName"></bean>


3、bean類

package com.test.pro;import java.util.List;public class Singer {private Instrument piano;public Instrument getPiano() {return piano;}public void setPiano(Instrument piano) {this.piano = piano;}public void saying(){System.out.println(piano.getName());}}

package com.test.pro;public class Instrument {private String name;public String getName() {return name;}public void setName(String name) {this.name = name;}}


輸出結果:


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.