【发布时间】:2021-10-17 14:43:13
【问题描述】:
我正在尝试使用 Autowired 从一个类中获取 bean。 我有类人
@Component("personBean")
public class Person {
@Autowired
@Qualifier("dog")
private Pet pet;
private String surname;
private int age;
public Person(Pet pet) {
this.pet = pet;
}
public void setSurname(String surname) {
this.surname = surname;
}
public void setAge(int age) {
this.age = age;
}
public void setPet(Pet pet) {
this.pet = pet;
}
public void callYourPet(){
System.out.println("Hello my pet");
pet.say();
}
}
也是狗类
@Component
public class Dog implements Pet{
public void init(){
System.out.println("Class dog: init method");
}
public void destroy(){
System.out.println("Class Dog:delete method");
}
@Override
public void say(){
System.out.println("Bow-Wow");
}
@Override
public String toString() {
return "Dog{Sobaka}";
}
}
猫类:
@Component
public class Cat implements Pet{
@Override
public void say() {
System.out.println("Meow-Meow");
}
}
当我试图从上下文中获取“personBean”Bean 时,我得到了这个异常
Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'personBean'. Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'spring_introduction.Pet' available: expected single matching bean but found 2: cat,dog
/////////////////////////////////////// //////////////////////////////////////////
【问题讨论】:
标签: java spring spring-boot