简体   繁体   English

使用注解配置引用多个 bean

[英]Refering multiple beans using annotation configuration

When using spring with xml configuration we can refer or add dependencies of multiple beans to one bean by writing the same similar code当使用 spring 和 xml 配置时,我们可以通过编写相同的类似代码来引用或添加多个 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>

Now I have below code I want to refer 2 cars beans per home bean I'm using qualifier to tackle ambiguity, could we refer multiple beans using qualifier or something else??现在我有下面的代码我想为每个家庭 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());
    }

One way to achieve this is to create one more reference of class car and using qualifier specifying the other bean name which works, is there any other way to achieve this?实现这一点的一种方法是再创建一个 class 汽车的引用,并使用限定符指定另一个有效的 bean 名称,还有其他方法可以实现吗?

Could we to achieve the same by using @Components ie one bean referring to multiple beans?我们可以通过使用@Components 来实现相同的目的,即一个bean 引用多个bean?

It's not possible to add multiple bean qualifiers to the same property.不可能将多个 bean 限定符添加到同一个属性。 However, you can have multiple properties of the same type.但是,您可以拥有多个相同类型的属性。 Something like this:像这样的东西:

@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

}

Another way to achieve the same is by using a Map , like this:另一种实现相同目的的方法是使用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

}

Using the map approach the key will be the qualifier name and the value will be the implementation for that qualifier.使用 map 方法, key将是qualifier名称,值将是该限定符的实现。

A working sample can be found on this GitHub repo 可以在此 GitHub 存储库中找到工作示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM