Gangmax Blog

自由之思想,独立之精神

Spring @Autowired Annotation

From here.

Today I just know that in Spring, if there are different bean instances with the same type, we can “autowire” all of them into a collection or a map of that common type. Such as:

1
// Assume we have multiple MovieCatalog Spring beans defined.
2
public class MovieRecommender {
3
4
    @Autowired
5
    private MovieCatalog[] movieCatalogs;
6
7
    // ...
8
}
9
// Or:
10
public class MovieRecommender {
11
12
    private Set<MovieCatalog> movieCatalogs;
13
14
    @Autowired
15
    public void setMovieCatalogs(Set<MovieCatalog> movieCatalogs) {
16
        this.movieCatalogs = movieCatalogs;
17
    }
18
19
    // ...
20
}
21
// Or:
22
public class MovieRecommender {
23
24
    private Map<String, MovieCatalog> movieCatalogs;
25
26
    @Autowired
27
    public void setMovieCatalogs(Map<String, MovieCatalog> movieCatalogs) {
28
        this.movieCatalogs = movieCatalogs;
29
    }
30
31
    // ...
32
}

Comments