Home > Blockchain >  No qualifying bean available: expected single matching bean but found 2
No qualifying bean available: expected single matching bean but found 2

Time:10-18

I am trying to get bean from one class using Autowired. I have class Person

@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();
    }
}

also class Dog

@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}";
    }
}

Cat class:

@Component
public class Cat implements Pet{

    @Override
    public void say() {
        System.out.println("Meow-Meow");
    }
}

When i am trying to get "personBean" Bean from context i get this exception

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

////////////////////////////////////////////////////////////////////////////////////////

CodePudding user response:

The below thread may help you in resolving the issue. It has explained that how autowiring for a child class can be done using parent class as reference.

Autowiring a subclass but using parent class as reference

CodePudding user response:

The issue is while creating a PersonBean. As you have a constructor which requires Pet instance to be passed. The constructor autowiring is complaining that there are 2 different beans available. So, the Qualifier should be added in the constructor not at Field level.

The Field injection should be removed as it is not needed.

Please try and change the code like below -

@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;
    }
  • Related