首页 > 编程语言 > 详细

Spring @qualifier @Required

时间:2015-08-03 01:19:39      阅读:389      评论:0      收藏:0      [点我收藏+]

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.配置文件

配置文件中有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方法必须定义为通过一个值来依赖注入。


Spring @qualifier @Required

原文:http://my.oschina.net/u/2308739/blog/486763

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!