How to resolve ambiguities in the AUTOMATIC CONNECTION of Bean in Spring? Image we have an interface:
public interface Dessert {
void eat();
}
And we have three Beans that implement the interface:
BEAN CAKE:
@Component
public class Cake implements Dessert{
@Override
public void eat() {
System.out.println("Eating a Cake !!!!");
}
}
BEAN COOKIE:
@Component
public class Cookie implements Dessert{
@Override
public void eat() {
System.out.println("Eating a Cookie !!!!");
}
}
BEAN ICECREAM:
@Component
public class IceCream implements Dessert{
@Override
public void eat() {
System.out.println("Eating a IceCream !!!!");
}
}
This would be the configuration file:
@Configuration
@ComponentScan
public class AutoBeanConfiguration {
}
This would be the Main class:
public class Main {
public static void main(String[] args) {
BasicConfigurator.configure();
Logger.getRootLogger().setLevel(Level.ERROR);
AnnotationConfigApplicationContext ctxt = new AnnotationConfigApplicationContext(AutoBeanConfiguration.class);
Dessert dessert = ctxt.getBean(Dessert.class);
dessert.eat();
ctxt.close();
}
}
The program throws the following exception: Exception in thread "main" org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'Dessert' available: expected single matching bean but found 3: cake, cookies, iceCream at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveNamedBean (DefaultListableBeanFactory.java:1041)
This happens because we have three desserts and Spring does not know which of them we want to eat.
How can we resolve the ambiguity and tell spring which of the Desserts do we want it to believe, to eat it?