8.2.3: 使用@Resource配置依賴

來源:互聯網
上載者:User

@Resource位於java.annotation包下,是來自JavaEE規範的一個Annotation,Spring直接借鑒了該Annotation,通過使用該Annotation為目標Bean指定共同作業者Bean。

@Resource有一個name屬性,預設情況下,Spring將這個值解釋為需要被注入的Bean執行個體的名字。換句話說,使用@Resource與<property.../>元素的ref屬性有相同的效果。

@Componentpublic class Chinese implements Person {private Axe axe;@Resource(name="stoneAxe")public void setAxe(Axe axe) {this.axe = axe;}@Overridepublic void useAxe() {System.out.println(axe.chop());}}

上面的@Resource Annotation指定將stoneAxe注入該setAxe( )方法,也就是將容器中的stoneAxe Bean作為setAxe方法的參數傳入。

@Resource不僅可以修飾setter方法,也可以直接修飾Field,使用@Resouce時還可以省略name屬性。使用@Resource修飾Field時連setter方法都可以不要:

@Componentpublic class Chinese implements Person {@Resource(name="stoneAxe")private Axe axe;@Overridepublic void useAxe() {System.out.println(axe.chop());}}

① 當使用@Resource修飾setter方法時,如果省略name屬性,例如@Resource標註setName( )方法,則Spring預設注入容器中名為name的組件。

② 當使用@Resource修飾Field時,如果省略name屬性,例如@Resource標註name Field,則Spring預設會注入容器中名為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.