为了账号安全,请及时绑定邮箱和手机立即绑定

在 Spring Boot 中具有相同实现的多个 bean

在 Spring Boot 中具有相同实现的多个 bean

繁花如伊 2022-01-19 17:19:25
我有一种情况,我正在为特定的 bean 使用一种可能的实现,它看起来像这样:@Configurationpublic class MyConfig {    @Autowired    private ApplicationContext context;    @Bean    public SomeInterface someInterface() {        if (this.context.getEnvironment().getProperty("implementation") != null) {            return new ImplementationOne();        } else {            return new ImplementationTwo();        }    }}到目前为止,这工作得很好,直到出现新的要求,使用一个额外的接口,目前只ImplementationTwo提供实现,使用它是没有意义的ImplementationOne:    @Bean    public SomeOtherInterface someOtherInterface() {            return new ImplementationTwo();    }我想这会起作用,但我想知道这是否真的有意义,因为在一种情况下,我可以让两个 bean 基本上实例化同一个对象。那有意义吗 ?有没有更好的方法来实现同样的目标?
查看完整描述

2 回答

?
波斯汪

TA贡献1811条经验 获得超4个赞

我相信,如果您有单个接口的多个实现,那么您应该使用以下特定的 bean 名称。


这里 implementation1 将是我们在 Interface1 依赖项中创建和注入的主要 bean。


@Primary

@Bean

public Interface1 implementation1() {

    return new Implementation2();

}


@Bean

public Interface1 implementation2() {

    return new Implementation2();

}

如果我们需要注入 implementation2,我们需要@Resource 注释,如下所示。


@Resource(name="implementation2")

Interface1 implementation2;


查看完整回答
反对 回复 2022-01-19
?
慕慕森

TA贡献1856条经验 获得超17个赞

您始终可以在使用特定 bean 的每个地方定义限定符:


   @Bean

   public SomeInterface beanName1(){ //impl }


   @Bean

   public SomeInterface beanName2(){ //impl }

用法:


 @Qualifier("beanName1") SomeInterface interface;

还需要在您的application.yml/properties文件中允许多个 bean:


spring.main.allow-bean-definition-overriding=true


查看完整回答
反对 回复 2022-01-19
  • 2 回答
  • 0 关注
  • 508 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信