【问题标题】:NoUniqueBeanDefinitionException: No qualifying bean of type : This is not returnedNoUniqueBeanDefinitionException:没有符合条件的 bean 类型:不返回
【发布时间】:2023-03-26 12:58:01
【问题描述】:

我将以下 bean 定义为 A.jar 的一部分

package abc;

@Component
public class ParentInterceptor implements ClientInterceptor {

}

我通过扩展 ParentInerceptor 在不同包下的不同项目中创建了另一个 bean

package xyz;

@Component
public class ChildInterceptor extends ParentInterceptor {

}

在我的 SpringBoot 应用程序中,我定义了一个类似于下面的 bean

@ComponentScan({"abc","xyz"})
public class Application {

    public static void main(String[] args) {
        ApplicationContext ctx =  SpringApplication.run(Application.class, args);
}

@Bean
public Data dataRepo(ParentInterceptor p){

}


}

当我运行 main 方法时,我希望看到 NoUniqueBeanDefinitionException 因为 2 个 bean 属于同一类型。但是,我看到两个 bean 都已加载并且 ParentInterceptor 正在使用中。没有抛出错误的原因是什么?

编辑

但是,当我执行以下操作时,我能够看到抛出的错误。但是我仍然无法理解为什么在上面列出的情况下没有抛出错误。

package xyz;

@Component
public class ChildInterceptor1 extends ChildInterceptor {

}

应用类:

 @ComponentScan({"abc","xyz"})
    public class Application {

        public static void main(String[] args) {
            ApplicationContext ctx =  SpringApplication.run(Application.class, args);
    }

    @Bean
    public Data dataRepo(ChildInterceptor p){

    }


    }

编辑 2

我还尝试使用以下代码检查子 bean 是否确实扩展了父级 -

ctx.getBeansOfType(ParentInterceptor.class)

这将返回 ParentInterceptor 和 ChildInterceptor。所以我不太确定为什么 Spring 没有返回错误!

【问题讨论】:

  • 我同意第一个案例应该失败。你能分享一个重现问题的完整示例吗?
  • 谢谢安迪。它是一个大型项目的一部分,但我无法创建一个独立的应用程序来复制这个问题。但是我仍在尝试这样做。
  • 是否有任何设置可以绕过此错误并注入适当的类?就我而言,我能够看到 ParentInterceptor 被注入。但是,当我在 ClientInterceptor 上设置 @Primary 注释时,正在注入 ClientInterceptor。是否有任何配置以及 SpringBootApplication 注释(约定优于配置),使 Spring 能够选择合适的 bean 而不会引发错误?抱歉,我仍然无法想出一个可以复制它的示例。我总是收到 NoUniqueBeanDefinitionException 并且看起来我缺少一些配置。
  • 你能添加一个 Spring 版本吗?
  • 嗨克里斯托弗,我正在使用 v 4.1.8

标签: java spring spring-boot


【解决方案1】:

在您的第一个示例(父母和孩子)中,我有正确的行为,即抛出 NoUniqueBeanDefinitionException。

如果要指定注入哪个bean,可以使用@Qualifier注解:

@Bean
public Data dataRepo(@Qualifier("parentInterceptor") ParentInterceptor p) {

}

您可以选择为组件命名:

@Component("foo") 

并相应地更改@Qualifier。

【讨论】:

    猜你喜欢
    • 2021-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-07
    • 1970-01-01
    • 1970-01-01
    • 2014-01-15
    相关资源
    最近更新 更多