有一个接口
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
问题是为什么它不起作用,因为我通过限定符指出了我应该使用哪个 bean?如果我在 Cat 或 Dog 类上方指定 @Primary 注释,那么一切都会神奇地开始工作,请告诉我这里有什么神奇之处,在此先感谢 :)
在您的示例中,
AnimalService它根本不起作用。该行Animal animal = applicationContext.getBean(Animal.class)试图从 context 获取一个类 beanAnimal,其中有两个。更正为或
您创建了 AnimalService 服务类并在其中指定了 @Qualifier,但您没有在任何地方使用此服务,而是立即在 Main 中调用 Animal。
尝试在Main中获取bean AnimalService,然后调用getAnimal()方法从中获取需要的Animal