加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

java – 没有@Primary的Spring @Qualifier不工作

发布时间:2020-12-15 01:41:12 所属栏目:大数据 来源:网络整理
导读:参见英文答案 What is a NoSuchBeanDefinitionException and how do I fix it?????????????????????????????????????1个 所以,我正在尝试用Spring Boot学习.我试过@Qualifier和@Autowired但它给了我以下错误: Parameter 0 of constructor in io.cptpackage.

参见英文答案 > What is a NoSuchBeanDefinitionException and how do I fix it?????????????????????????????????????1个
所以,我正在尝试用Spring Boot学习.我试过@Qualifier和@Autowired但它给了我以下错误:

Parameter 0 of constructor in io.cptpackage.springboot.bootdemo.BinarySearch required a single bean,but 2 were found:

即使我提供了正确的@Qualifier它也不起作用,直到其中一个依赖项有一个@Primary注释,名称引用也不起作用我使用@Primary或??@Qualifier并且你知道我有问题用@Qualifier的东西.代码很简单,如下所示.

@Component 
public class BinarySearch {

// Sort,Search,Return the result!
@Autowired
@Qualifier("quick")
Sorter sorter;

public BinarySearch(Sorter sorter) {
    super();
    this.sorter = sorter;
}

public int search(int[] numbersToSearchIn,int targetNumber) {
    sorter.sort(numbersToSearchIn);
    return targetNumber;
 } 
}

第一个依赖:

@Component
@Qualifier("bubble")
public class BubbleSort implements Sorter {

    @Override
    public int[] sort(int[] targetArray) {
        System.out.println("Bubble sort!");
        return targetArray;
    }

}

第二个依赖:

@Component
@Qualifier("quick")
public class QuickSort implements Sorter {

    @Override
    public int[] sort(int[] targetArray) {
        System.out.println("Quick Sort!");
        return targetArray;
    }

}

另外,为什么名称自动装配不起作用?

最佳答案
@Qualifier是一个注释,用于指定需要注入的bean,它与@Autowired一起使用.

如果你需要指定一个组件的名称,只需要命名@Component(“myComponent”),然后当你需要注入它时使用@Qualifier(“myComponent”)

对于你的问题,试试这个:

代替:

@Component
@Qualifier("bubble")
public class BubbleSort implements Sorter {

用这个:

@Component("quick")
public class BubbleSort implements Sorter {

最后定义一种注入bean的方法,例如:

选项1:构造函数参数

@Component 
public class BinarySearch {

// Sort,Return the result!
private final Sorter sorter;

public BinarySearch(@Qualifier("quick")Sorter sorter) {
    super();
    this.sorter = sorter;
}

选项2作为集体成员

@Component 
public class BinarySearch {

// Sort,Return the result!
@Autowired
@Qualifier("quick")
Sorter sorter;

public BinarySearch() {
    super();

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读