spring - 常用注解@Qualifier

一、简介

@Qualifier是org.springframework.beans.factory.annotation下面的一个很实用的注解.对其的描述是:

*此注释可以作为字段或参数的限定符使用

*自动装配时的候选bean。它也可以用来注释其他

*自定义注释,然后可以作为限定符使用

二、使用场景

当存在两个类型一致的bean时,自动注入的时候并不知道我们需要引入哪一个bean所以此时需要@Qualifier(“xxxx”)来进行指定。
否则会出现

org.springframework.beans.factory.NoUniqueBeanDefinitionException:
 No qualifying bean of type 'com.xxx.xxx' available: 
 expected single matching bean but found xxx次数

例子:

  
    @Bean("queueD")
    public Queue queueD() {
    
    
        return new Queue(DEAD_LETTER_QUEUE);
    }
    @Bean("queueB")
    public Queue queueB() {
    
    
        return new Queue(DEAD_LETTER_QUEUE);
    }
    
   @Bean
   //在此执行我们要导入某个类型下的哪一个进来
    public void deadLetterBindingQAD(@Qualifier("queueD") Queue){
    
    
    	.....
    } 

猜你喜欢

转载自blog.csdn.net/weixin_46266624/article/details/131291265