微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

参见英文答案 > 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();

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐