BubbleSort.java This class implements SortAlgorithm interface
package com.prakash.Spring.Example;
import org.springframework.stereotype.Component;
@Component
@Qualifier("bubbleSort")
public class BubbleSort implements SortAlgorithm {
public void sort() {
System.out.println("Sort from Bubble Sort");
}
}
QuickSort.java This class implements SortAlgorithm interface package com.prakash.Spring.Example;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
@Component
@Qualifier("quickSort")
public class QuickSort implements SortAlgorithm {
@Override
public void sort() {
System.out.println("Sort from Quick Sort");
}
}
SortAlgorithm.java
package com.prakash.Spring.Example;
public interface SortAlgorithm {
void sort();
}
BinarySearch.java In this class, I would like to use quickSort bean as my component.
package com.prakash.Spring.Example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
@Component
public class BinarySearch {
@Autowired
@Qualifier("quickSort")
private SortAlgorithm sortAlgorithm;
public BinarySearch(SortAlgorithm sortAlgorithm) {
super();
this.sortAlgorithm = sortAlgorithm;
}
public int[] search(int[] numbers) {
sortAlgorithm.sort();
System.out.println("This is from BinarySearch");
return numbers;
}
}
ComplexBusinessService.java In this class, I'm getting the bean using getBean method
package com.prakash.Spring.Example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class ComplexBussinessService {
public static void main(String[] args) {
ConfigurableApplicationContext applicationContext = SpringApplication.run(ComplexBussinessService.class, args);
BinarySearch binarySearch = applicationContext.getBean(BinarySearch.class);
int[] result = binarySearch.search(new int[] { 2, 4, 3 });
for (int i : result) {
System.out.print(i+" ");
}
applicationContext.close();
}
}