首页 > 解决方案 > java - 如何在运行时自动装配java spring中的对象,因为它有多个子类?

问题描述

例如:我有一个类似的界面

class TestAnimal {

    @Autowired
    @Qualifier("animal")
    private @IAnimal animal;

    void hanlde (){
        animal.some();
    }
}
interface IAnimal {
    void some();
}

@Component
class Lion implements IAnimal{
    void some(){}
}

@Component
class Tiger implements IAnimal{
    void some(){}
}

@Component
class Hippo implements IAnimal{
    void some(){}
}

当我运行服务器时,我遇到了异常

原因:org.springframework.beans.factory.NoUniqueBeanDefinitionException:没有“com.test.Animal”类型的合格 bean 可用:预期单个匹配 bean,但在 org.springframework.beans.factory.config 中找到了 3:Lion、Tiger、Hippo .DependencyDescriptor.resolveNotUnique(DependencyDescriptor.java:173)。

如何解决这个问题。有什么方法可以创建运行时对象初始化?

标签: javaspring

解决方案


Spring 不知道要注入哪个 bean。您的代码中有三个豆子:狮子、老虎和河马。因此,在动物字段上方,您应该使用 @Qualifier 注释选择要注入的 bean。例如,如果它是一头狮子,你必须写 @Qualifier("lion")。并删除“私人@IAnimal 动物;”行中的@。

如果您想要动态自动装配,您应该查看https://www.baeldung.com/spring-dynamic-autowire


推荐阅读