【问题标题】:Qualify bean based on the bean name in springspring 根据 bean 名称限定 bean
【发布时间】:2018-02-23 05:55:05
【问题描述】:

从标题来看,这似乎很简单,我们在应用程序中使用 @qualify 和 @autowired 在代码中注入 bean。

我有两个具有@component 注释的类,它们都实现了相同的类。

@Component
class A extends B{  
}

@Component
class C extends B{  
}

当应用程序在启动应用程序时作为相同类型的两个 bean 启动时,应用程序将失败并出现以下错误

org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'JI' available: expected single matching bean but found 2: a,b

问题是我没有注入这些 bean,spring 正在注入我想告诉 spring 通过 bean 名称而不是类型运行时注入这些 bean。

应用程序在第一个请求到来时启动良好,但失败并给出错误。

我在下面试过这个 -

@Component
@Qualifier("a")
class A extends B{  
}

@Component
@Qualifier("c")
class C extends B{  
}

但仍然得到同样的错误。

关于如何使这项工作正常的任何建议。

【问题讨论】:

    标签: spring


    【解决方案1】:

    注入时必须使用 bean 的名称。

       @Autowired
       @Qualifier("c") // or "a"
       private TargetClass targetClass;
    

    【讨论】:

    • 感谢您的回答。但这不是我所期待的。正如我告诉你的那样,我不会在课堂上自动装配它们。我只是在创建组件,它们属于同一类型。
    • 您是否尝试过清理并再次构建项目?
    • com.hsbcib.securities.ecomlib.job.JobImplementation 你在哪里使用它们?贴出代码
    • org.springframework.beans.factory.NoUniqueBeanDefinitionException:没有“JI”类型的合格 bean 可用:预期单个匹配 bean,但找到 2:a,b
    • 这来自我用作 maven 依赖项的库,我无法编辑该代码。
    猜你喜欢
    • 1970-01-01
    • 2020-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-28
    • 2011-05-05
    • 1970-01-01
    相关资源
    最近更新 更多