2.19 @Qualifier注解

戴着假发的程序员出品  抖音ID:戴着假发的程序员  欢迎关注

[查看视频教程]

查看源码:

1 package org.springframework.beans.factory.annotation;
2 
3 @java.lang.annotation.Target({java.lang.annotation.ElementType.FIELD, java.lang.annotation.ElementType.METHOD, java.lang.annotation.ElementType.PARAMETER, java.lang.annotation.ElementType.TYPE, java.lang.annotation.ElementType.ANNOTATION_TYPE})
4 @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
5 @java.lang.annotation.Inherited
6 @java.lang.annotation.Documented
7 public @interface Qualifier {
8     java.lang.String value() default "";
9 }

@Qualifirer主要用来指定要注入的bean的限定符(beanName)。

当我们需要注入某个类型的bean时,同时spring容器中有多同样类型的bean,这时我们可以通过@Qualifirer指定要注入的beanName。

用法如下:

[1]可以和@Autowired配合使用

 1 /**
 2  * @author 戴着假发的程序员
 3  *  
 4  * @description
 5  */
 6 @Component
 7 public class ArticleService {
 8     @Autowired
 9     @Qualifier("articleDAO_mysql")
10     private IAutorDAO autorDAO;
11    //...
12 }

[2]也可以在setter方法的参数上使用

 1 /**
 2  * @author 戴着假发的程序员
 3  *  
 4  * @description
 5  */
 6 @Component
 7 public class ArticleService {
 8     @Autowired
 9     private IAutorDAO autorDAO;
10     public void setAutorDAO(@Qualifier("articleDAO_mysql") IAutorDAO autorDao){
11         this.autorDAO = autorDao;
12     }
13    //...
14 }

[3]也可以在构造方法中使用

 1 /**
 2  * @author 戴着假发的程序员
 3  *  
 4  * @description
 5  */
 6 @Component
 7 public class ArticleService {
 8     @Autowired
 9     private IAutorDAO autorDAO;
10     public ArticleService(@Qualifier("articleDAO_mysql") IAutorDAO autorDao){
11         this.autorDAO = autorDao;
12     }
13    //...
14 }

[4]你还可以扩展自己的限定符注解

1 @Target({ElementType.FIELD, ElementType.PARAMETER})
2 @Retention(RetentionPolicy.RUNTIME)
3 @Qualifier
4 public @interface Genre {
5     String value();
6 }

 

posted @ 2020-10-10 08:27  戴着假发的程序员0-1  阅读(276)  评论(0编辑  收藏  举报