【问题标题】:No qualifying bean available: expected single matching bean but found 2没有可用的合格 bean:预期单个匹配 bean,但找到了 2
【发布时间】: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


    【解决方案1】:

    问题出在创建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;
        }
    

    【讨论】:

    • 是的,问题出在构造函数中。我从构造函数中删除了 pet 参数,并在 pet 参数上保留了 Autowired 和 Qualifier,一切正常。谢谢
    【解决方案2】:

    以下线程可能会帮助您解决问题。它解释了如何使用父类作为参考来完成子类的自动装配。

    Autowiring a subclass but using parent class as reference

    【讨论】:

      猜你喜欢
      • 2019-04-08
      • 2018-02-08
      • 2018-10-05
      • 2017-12-11
      • 2019-08-06
      • 2021-06-14
      • 1970-01-01
      • 2016-04-12
      • 2018-04-22
      相关资源
      最近更新 更多