Есть интерфейс
package ioc.primary_annotation;
public interface Animal {
void display();
}
его реализуют два класса
package ioc.primary_annotation;
import org.springframework.stereotype.Component;
@Component("kitty")
public class Cat implements Animal {
public void display() {
System.out.println("Cat.display");
}
}
и
package ioc.primary_annotation;
import org.springframework.stereotype.Component;
@Component("doggi")
public class Dog implements Animal {
public void display() {
System.out.println("Dog.display");
}
}
есть класс конфигурации
package ioc.primary_annotation;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "ioc.primary_annotation")
public class AppConfig {
}
и сервис
package ioc.primary_annotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;;
import org.springframework.stereotype.Service;
@Service
public class AnimalService {
@Autowired
@Qualifier("kitty")
private Animal animal;
public AnimalService() {
}
public Animal getAnimal() {
return animal;
}
public void setAnimal(Animal animal) {
this.animal = animal;
}
}
и всё это должно работать в методе main
package ioc.primary_annotation;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class PrimaryMain {
public static void main(String[] args) {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
Animal animal = applicationContext.getBean(Animal.class);
animal.display();
}
}
Но не работает, падает исключение
Exception in thread "main" org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'ioc.primary_annotation.Animal' available: expected single matching bean but found 2: kitty,doggi
Вопрос в том почему это не работает, ведь я указал через Qualifier какой бин нжуно использовать? Если я над классом Cat или Dog укажу анотацию @Primary, то всё магическим образом начинает работать, подскажите в чём здесь магия, за ранее спасибо :)
В вашем примере AnimalService вообще никак не задействован. Строка Animal animal = applicationContext.getBean(Animal.class) пытается получить из контекста бин класса Animal, а там таких два. Исправьте на
Animal animal = applicationContext.getBean("kitty", Animal.class)
или на
AnimalService animalService = applicationContext.getBean(AnimalService.class)
Вы создали класс сервис AnimalService и указали в нём @Qualifier, но этот сервис вы нигде не используете, а сразу в Main вызываете Animal.
Попробуйте в Main получать bean AnimalService, а затем из него получать нужный Animal путём вызова метода getAnimal()
Апостиль в Лос-Анджелесе без лишних нервов и бумажной волокиты
Основные этапы разработки сайта для стоматологической клиники
Продвижение своими сайтами как стратегия роста и независимости