[英]NoUniqueBeanDefinitionException: No qualifying bean of type : This is not returned
I have the below bean defined as part a A.jar 我将下面的bean定义为A.jar的一部分
package abc;
@Component
public class ParentInterceptor implements ClientInterceptor {
}
I have created another bean in a different project under a different package by extending ParentInerceptor 我通过扩展ParentInerceptor在不同的包下创建了另一个bean
package xyz;
@Component
public class ChildInterceptor extends ParentInterceptor {
}
In my SpringBoot app , I have a bean defined similar to below 在我的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){
}
}
When I run the main method , I am expecting to see NoUniqueBeanDefinitionException as 2 beans are of same type. 当我运行main方法时,我希望看到NoUniqueBeanDefinitionException,因为2个bean的类型相同。 However I see both the beans are loaded and ParentInterceptor is being used.
但是我看到两个bean都已加载并且正在使用ParentInterceptor。 Is there a reason why the error is not being thrown?
有没有理由不抛出错误?
EDIT 编辑
However when i did the below , I was able to see the error being thrown. 但是,当我执行下面的操作时,我能够看到错误被抛出。 However I am still unable to understand why an error wasn't thrown in the case listed above.
但是我仍然无法理解为什么在上面列出的情况下没有抛出错误。
package xyz;
@Component
public class ChildInterceptor1 extends ChildInterceptor {
}
Application Class: 申请类别:
@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){
}
}
EDIT 2 编辑2
I also tried to check if the child bean indeed extending the parent using the code below - 我还尝试使用下面的代码检查子bean是否确实扩展了父级 -
ctx.getBeansOfType(ParentInterceptor.class)
This returns ParentInterceptor & ChildInterceptor. 这将返回ParentInterceptor和ChildInterceptor。 So I am not really sure why Spring is not returning the error!
所以我不确定为什么Spring没有返回错误!
In your first example (Parent and Child), i have the correct behaviour, which is the NoUniqueBeanDefinitionException thrown. 在您的第一个示例(Parent和Child)中,我有正确的行为,即抛出NoUniqueBeanDefinitionException。
If you want to specify which bean to be injected, you can use the @Qualifier annotation: 如果要指定要注入的bean,可以使用@Qualifier注释:
@Bean
public Data dataRepo(@Qualifier("parentInterceptor") ParentInterceptor p) {
}
Optionally, you can give a name to a component: (可选)您可以为组件指定名称:
@Component("foo")
and change the @Qualifier accordingly. 并相应地更改@Qualifier。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.