Como resolver ambiguedades en la CONEXION AUTOMATICA de Bean en Spring? Imagenemos que tenemos una interfaz Postre, y tenemos tres postres diferentes (Beans) que implementan la interfaz(Dessert).
El postre del dia es Cookie, por lo tanto lo anotamos como favorito con @Primary
.
El problema, es que se han hecho los postres justos y si alguien quiere repetir postre, no habra mas Cookies, por lo que hemos creado "repeatDessert" para aquellos que quieran repetir postre.
Ademas del postre favorito, existen dos postres mas, CAKE Y ICECREAM.
Queremos que a todos los que repitan se le sirva de postre IceCream, del que tenemos cantidad suficiente.
¿como podemos decirle a Spring cual de los dos postres es que el queremos que sirva?
public interface Dessert {
void eat();
}
BEAN CAKE:
@Component
public class Cake implements Dessert{
private Dessert repeatDessert;
public Dessert getRepeatDessert() {
return repeatDessert;
}
@Autowired
public void setRepeatDessert(Dessert repeatDessert) {
this.repeatDessert = repeatDessert;
}
@Override
public void eat() {
System.out.println("Eating a Cake !!!!");
}
}
BEAN COOKIE:
@Component
@Primary
public class Cookie implements Dessert{
private Dessert repeatDessert;
public Dessert getRepeatDessert() {
return repeatDessert;
}
@Autowired
public void setRepeatDessert(Dessert repeatDessert) {
this.repeatDessert = repeatDessert;
}
@Override
public void eat() {
System.out.println("Eating a Cookie !!!!");
}
}
BEAN ICECREAM:
@Component
public class IceCream implements Dessert{
private Dessert repeatDessert;
public Dessert getRepeatDessert() {
return repeatDessert;
}
@Autowired
public void setRepeatDessert(Dessert repeatDessert) {
this.repeatDessert = repeatDessert;
}
@Override
public void eat() {
System.out.println("Eating a IceCream !!!!");
}
}
Este seria el archivo de configuracion:
@Configuration
@ComponentScan
public class AutoBeanConfiguration {
}
Esta seria la clase Main:
public class Main {
public static void main(String[] args) {
BasicConfigurator.configure();
Logger.getRootLogger().setLevel(Level.ERROR);
AnnotationConfigApplicationContext ctxt = new AnnotationConfigApplicationContext(AutoBeanConfiguration.class);
Cookies cookies = ctxt.getBean(Cookies.class);
cookies.eat();
Dessert dessert = cookies.getRepeatDessert();
dessert.eat();
ctxt.close();
}
}
El programa arroja la siguiente excepcion
:
Exception in thread "main" Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'cookies': Unsatisfied dependency expressed through method 'setRepeatDessert' parameter 0;
org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'Dessert' available: expected single matching bean but found 2: cake,iceCream
Como podemos resolver la ambiguedad y decirle a spring cual de los Postres queremos que cree, cuando queremos repetir?
La salida por consola deberia ser esta:
Eating a Cookies !!!!
Eating a IceCream !!!!