我正在嘗試使用 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
///////////////////////////////////////////////// //////////////////////////////////////
uj5u.com熱心網友回復:
下面的執行緒可以幫助您解決問題。它解釋了如何使用父類作為參考來完成子類的自動裝配。
自動裝配子類但使用父類作為參考
uj5u.com熱心網友回復:
問題是在創建PersonBean. 因為您有一個需要Pet傳遞實體的建構式。建構式自動裝配抱怨有 2 個不同的 bean 可用。因此,應該在建構式中而不是在欄位級別添加限定符。
應洗掉欄位注入,因為它不需要。
請嘗試更改如下代碼 -
@Component("personBean")
public class Person {
// @Autowired // not needed
// @Qualifier("dog") // not needed
private Pet pet;
private String surname;
private int age;
public Person(@Qualifier("dog") Pet pet) { // added a qualifier
this.pet = pet;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/322713.html
