【问题标题】:Refering multiple beans using annotation configuration使用注解配置引用多个 bean
【发布时间】:2020-07-19 16:53:15
【问题描述】:

当使用带有xml配置的spring时,我们可以通过编写相同的类似代码来引用或添加多个bean的依赖项到一个bean

<beans>
   <bean id ="parent" class="com.Parent">
   <property name = "child1" ref = "child1"/>
   <property name = "child2" ref = "child2"/>
   </bean>

   <bean id = "child1" class="com.child">
   <property name = "name" value = "abc"/>
   </bean>

   <bean id = "child2" class="com.child">
   <property name = "name" value = "xyz"/>
   </bean>
</beans>

现在我有下面的代码,我想为每个家庭 bean 引用 2 个汽车 bean 我正在使用限定符来解决歧义,我们可以使用限定符或其他方式引用多个 bean 吗??


Configfile.java

        @Bean("jeep")
    public Car returnJeep()
    {
        Car c = new Car();
        c.setName("Wrangler");
        return c;
    }

    @Bean("volvo")
    public Car returnVolvo()
    {
        Car c = new Car();
        c.setName("Volvo");

        return c;
    }

Home.java

    @Autowired
    @Qualifier("volvo,jeep") --> How can I refer multiple beans here????
    private Car car;

    @Override
    public void print() {
        System.out.println("Cheers!!, now you own a new home and a "+ car.getName());
    }

实现这一点的一种方法是再创建一个 car 类的引用并使用限定符指定另一个有效的 bean 名称,还有其他方法可以实现吗?

我们是否可以通过使用@Components 来实现相同的目的,即一个 bean 引用多个 bean?

【问题讨论】:

  • 我想你需要的是decorator pattern

标签: java spring annotations spring-annotations spring-bean


【解决方案1】:

不能将多个 bean 限定符添加到同一个属性。但是,您可以拥有多个相同类型的属性。像这样的:

@Component
public class Home {

    private final Car Volvo;
    private final Car jeep;

    public Home(@Qualifier("volvo") Car volvo, @Qualifier("jeep") Car jeep) {
        this.volvo = volvo;
        this.jeep = jeep;
    }

    // your code goes here

}

实现相同目的的另一种方法是使用Map,如下所示:

@Component
public class Home {

    private final Map<String, Car> carMap;
    private final Car jeep;

    public Home(Map<String, Car> carMap) {
        this.carMap = carMap;
    }

    // your code goes here

}

使用映射方法,key 将是 qualifier 名称,值将是该限定符的实现。

A working sample can be found on this GitHub repo

【讨论】:

  • 上述方法不起作用,导致异常,无论如何我会尝试其他一些解决方法,你的方法确实让我的大脑更深入地思考。谢谢
  • 哪个例外?
  • 没有 'com.SpringTrial.Car' 类型的合格 bean 可用:预计至少有 1 个有资格作为自动装配候选者的 bean。依赖注解:{@org.springframework.beans.factory.annotation.Qualifier(value=volvo)}
  • 很抱歉,这与我向您展示的内容无关,您只是没有声明 bean,您将无法注入未声明的内容。
  • 我已将 bean Car 声明为 @Component,并且在 Home.java 中我将它们声明为私有 final 字段,如上所示,我错过了其他内容,因为它在我'正在创建一个 Car 的引用而不使用限定符。
猜你喜欢
  • 2011-04-24
  • 1970-01-01
  • 1970-01-01
  • 2013-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-15
相关资源
最近更新 更多