Spring @qualifier @Required

來源:互聯網
上載者:User

標籤:

B、@Qualifier

org.springframework.beans.factory.annotation.Qualifier

public @interface Qualifier

This annotation may be used on a field or parameter as a qualifier for candidate beans when autowiring. It may also be used to annotate other custom annotations that can then in turn be used as qualifiers.

@Qualifier用於注釋一個欄位或參數,當自動綁定時它作為候選bean的限定器。它也可以用於自訂的限定器注釋。

 

屬性

value

 

B.1、舉例說明

我們使用@AutoWired按照類型自動綁定,當容器中有多個匹配的bean時,將綁定那一個呢?我們可以通過在需要綁定的欄位或參數上使用@Qualifier(value=” bar1”)來指定要綁定的bean。並在bean定義中使用<bean id="bar1"或<qualifier value="bar1"/>來關聯。

 

範例1

1.Foo類

 

Java代碼  

  1. public class Foo {    

  2.     @Autowired  

  3.     @Qualifier(value="bar1")  

  4.     private Bar bar;  

  5. }  

 

2.設定檔

設定檔中有2個Bar,一個bean使用qualifier進行標註,一個使用id進行標註,容器將選擇和@Qualifier(value)匹配的bean來進行綁定。

 

Xml代碼  

  1. <beans>  

  2.     <context:annotation-config/>  

  3.     <bean id="foo" class="x.y.Foo" />  

  4.     <bean class="x.y.Bar">  

  5.        <qualifier value="bar2"/>  

  6.        <property name="a" value="bar2" />  

  7.     </bean>  

  8.     <bean id="bar1" class="x.y.Bar">  

  9.        <property name="a" value="bar1" />  

  10.     </bean>  

  11. </beans>  

 


C、@Required

org.springframework.beans.factory.annotation.Required

public @interface Required

Marks a method (typically a JavaBean setter method) as being ‘required‘: that is, the setter method must be configured to be dependency-injected with a value.

標註一個方法(通常是一個JavaBean的setter方法)是@Required,也就是,這個setter方法必須定義為通過一個值來依賴注入。


Spring @qualifier @Required

聯繫我們

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