Spring @qualifier @Required

B、@Qualifierspring

org.springframework.beans.factory.annotation.Qualifierui

public @interface Qualifierspa

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..net

@Qualifier用於註釋一個字段或參數,當自動綁定時它做爲候選bean的限定器。它也能夠用於自定義的限定器註釋。orm

 

屬性get

valueit

 

B.一、舉例說明io

咱們使用@AutoWired按照類型自動綁定,當容器中有多個匹配的bean時,將綁定那一個呢?咱們能夠經過在須要綁定的字段或參數上使用@Qualifier(value=」 bar1」)來指定要綁定的bean。並在bean定義中使用<bean id="bar1"<qualifier value="bar1"/>來關聯。class

 

範例1容器

1.Foo

 

Java代碼  收藏代碼

  1. public class Foo {    

  2.     @Autowired  

  3.     @Qualifier(value="bar1")  

  4.     private Bar bar;  

  5. }  

 

2.配置文件

配置文件中有2Bar,一個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方法必須定義爲經過一個值來依賴注入。

相關文章
相關標籤/搜索