Autowiring a map

In this post under Spring Core, I will show with example how to autowire a map.

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

Dao class

package package23;

public class Dao {
}

Below is the main class that shows how to autowire a map

Main class

1  package package23;
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.Map;
10 
11 @Configuration
12 public class Example23 {
13     @Autowired
14     private Map<String, Dao> daos;
15 
16     @Bean
17     protected Dao jmsDao() {
18         return new Dao();
19     }
20 
21     @Bean
22     protected Dao dbDao() {
23         return new Dao();
24     }
25 
26     public Map<String, Dao> getDaos() {
27         return this.daos;
28     }
29 
30     public static void main(String[] args) {
31         ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Example23.class);
32         Example23 example = applicationContext.getBean(Example23.class);
33         for(Map.Entry<String, Dao> entry : example.getDaos().entrySet()) {
34             System.out.println("Key: " + entry.getKey());
35             System.out.println("Value: " + entry.getValue());
36         }
37     }
38 }

In the above code, I have annotated the Main class with “@Configuration” annotation.

Created a private map field named “daos” with key type being a string and value type being “Dao” class.

Created two bean definition methods which will create two “Dao” instances one for jms and another for database.

Now Spring framework will populate the map “daos” with key name being the bean definition method name and value will being the instances returned from the bean definition methods.

In this way we can autowire a map.

Below is the output for your reference

Output

Key: jmsDao
Value: package23.Dao@561b6512
Key: dbDao
Value: package23.Dao@2e377400

Leave a comment