简体   繁体   中英

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

<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??


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?

Could we to achieve the same by using @Components ie one bean referring to multiple beans?

It's not possible to add multiple bean qualifiers to the same property. 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:

@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.

A working sample can be found on this GitHub repo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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