CallingApp.java
@Service
@ComponentScan(basePackages = { "com.codegeekslab.type" })
public class CallingApp {
@Autowired
@Qualifier("BasicPhone")
private Phone phone;
public CallingApp(Phone phone) {
this.phone = phone;
}
public void makeCall(int number) {
phone.openApp(number);
}
}
Phone.java
package com.geekslab.device;
public interface Phone {
public void openApp(int number);
}
BasicPhone.java
package com.codegeekslab.type;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import com.geekslab.device.Phone;
@Component("BasicPhone")
public class BasicPhone implements Phone {
{
System.out.println("BasicPhone");
}
public void openApp(int number) {
System.out.println("calling via simcard... " + number);
}
}
SmartPhone.java
package com.codegeekslab.type;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import com.geekslab.device.Phone;
@Component("SmartPhone")
public class SmartPhone implements Phone {
{
System.out.println("SmartPhone");
}
public void openApp(int number) {
System.out.println("calling via whatsapp..." + number);
}
}
Test.java
package com.codegeekslab.test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.codegeekslab.app.CallingApp;
import com.codegeekslab.type.BasicPhone;
import com.codegeekslab.type.SmartPhone;
import com.geekslab.device.Phone;
public class Test {
public static void main(String[] args) {
//ApplicationContext context =
// new GenericXmlApplicationContext("beans.xml");
//SpringHelloWorld helloSpring = context.getBean("springHelloWorld", SpringHelloWorld.class);
//comment this for xml less spring
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.scan("com.codegeekslab.app","com.codegeekslab.type");
//context.register( BasicPhone.class,SmartPhone.class,CallingApp.class);
context.refresh();
CallingApp callingApp = context.getBean("callingApp", CallingApp.class);
callingApp.makeCall(99999);
}
}
Even though i am giving qualifier as @Qualifier("BasicPhone")
in CallingApp
class ,I am getting Exception as follows:
No qualifying bean of type [com.geekslab.device.Phone] is defined: expected single matching bean but found 2: BasicPhone,SmartPhone
You pass phone as a constructor argument in your CallingApp service without specifying the bean.
Try either to put a qualifier at your constructor or stick to the autowire injection which is something your already do.