Autowiring a collection and array of beans

In this post under Spring Core, I will explain with example how to autowire a collection and array of beans.

For our example I will use the below “Dao” class

Dao class

package package22;

public class Dao {
    private String daoName;

    public Dao(String daoName) {
        this.daoName = daoName;
    }

    @Override
    public String toString() {
        return this.daoName;
    }
}

Next I will show the Main class annotated with “@Configuration” annotation and where I will create a collection and array of beans.

Main class

1  package package22;
2  
3  import org.springframework.beans.factory.annotation.Autowired;
4  import org.springframework.context.ApplicationContext;
5  import org.springframework.context.annotation.AnnotationConfigApplicationContext;
6  import org.springframework.context.annotation.Bean;
7  import org.springframework.context.annotation.Configuration;
8  
9  import java.util.List;
10 
11 @Configuration
12 public class Example22 {
13     @Autowired
14     private List<Dao> daoList;
15 
16     @Autowired
17     private Dao[] daoArray;
18 
19     @Bean
20     protected Dao jmsDao() {
21         return new Dao("JMSDao");
22     }
23 
24     @Bean
25     protected Dao dbDao() {
26         return new Dao("DBDao");
27     }
28 
29     public List<Dao> getDaoList() {
30         return daoList;
31     }
32 
33     public Dao[] getDaoArray() {
34         return this.daoArray;
35     }
36 
37     public static void main(String[] args) {
38         ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Example22.class);
39         Example22 example = applicationContext.getBean(Example22.class);
40         System.out.println("Browsing the list");
41         for(Dao dao : example.getDaoList()) {
42             System.out.println(dao);
43         }
44         System.out.println("Browsing the array");
45         for(Dao dao : example.getDaoArray()) {
46             System.out.println(dao);
47         }
48     }
49 }

In the above code, the main class is annotated with “@Configuration” annotation.

It has a private list field named “daoList” and array field named “daoArray”.

Next I have added bean definitions for two instances of “Dao” class, one for jms and another for database.

What the Spring framework will do when the program is run is that it will search for methods annotated with “@Bean” and having “Dao” class as return type, calls them to get the instances and inject them
in “daoList” and “daoArray” fields.

By default Spring framework uses data type of the array to find the bean definitions. In other words Spring framework is autowiring by type.

In this way we can tell Spring framework to autowire collection or array of beans.

Leave a comment