当使用@Qualifier指定的bean注入点时如何扩展命名的Spring bean?

问题描述 投票:0回答:1

如何使用@Qualifier指定的bean注入点扩展命名的bean?

我有由3个 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

java spring inversion-of-control autowired
1个回答
0
投票

您不能指定两个具有相同限定名称的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) {

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.