CptPackage CptPackage - 2 months ago 31
Java Question

Spring @Qualifier isn't working without @Primary

So, I am trying to learn my way with Spring Boot. I tried @Qualifier and @Autowired but it gives me the following error:


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


Even tho I have provided the right @Qualifier it doesn't work until one of the dependencies has a @Primary annotation, also the name reference doesn't work I to use @Primary or @Qualifier and you know that I am having the issue with the @Qualifier thing. The code is simple and as following.

@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;
}
}


The first dependency:

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

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

}


The second dependency:

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

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

}


Also why is autowiring by name isnot working?

Answer Source

@Qualifier is an annotation to specify the bean that you need to inject, it works together with @Autowired.

ff you need to specify the name of a component just put a name @Component("myComponent") and after that when you need to inject it use @Qualifier("myComponent")

For your question try this:

Instead of:

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

Use this:

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

And finally define one way to inject the bean for example:

Option 1: constructor parameter

@Component 
public class BinarySearch {

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

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

Option 2 as a class member

@Component 
public class BinarySearch {

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

public BinarySearch() {
    super();

}