如何使用@Qualifier
指定的bean注入点扩展命名的bean?
我有由3个spring bean组成的项目1:
@Component("bean1")
public class Bean1 implements Bean {
}
@Component("bean2")
public class Bean2 implements Bean {
}
@Component("bean3")
public class Bean3 {
private Bean bean;
public void setBean(@Qualifier("bean1") final Bean bean) {
this.bean = bean;
}
}
此项目被捆绑到一个jar中,并作为对我的第二个项目的依赖项包括在内:
@Component("bean1")
@Primary
public class Bean1Child extends Bean1 {
}
我想发生的是将Bean1Child
Bean注入到Bean3
的setter方法中。不幸的是,我收到一个错误。
org.springframework.context.annotation.ConflictingBeanDefinitionException:Bean类[Bean1Child]的注释指定的Bean名称'bean1'与现有的同名不兼容的Bean定义冲突和类[Bean1]
我需要使用@Qualifier
,以便不将Bean2
注入Bean3
中。使用@Primary
批注没有帮助。从第二个项目运行时,如何将Bean1Child
注入Bean3
?
您不能指定两个具有相同限定名称的bean,因为错误表明:
Annotation-specified bean name 'bean1' for bean class [Bean1Child]
conflicts with existing, non-compatible bean definition of same name and class [Bean1]
为Bean1Child提供不同的限定符名称应该起作用。
@Component("bean1child")
@Primary
public class Bean1Child extends Bean1 {
}
并且在Bean3中,public void setBean(@Qualifier("bean1child") final Bean bean) {