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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// Assume we have multiple MovieCatalog Spring beans defined.
public class MovieRecommender {

@Autowired
private MovieCatalog[] movieCatalogs;

// ...
}
// Or:
public class MovieRecommender {

private Set<MovieCatalog> movieCatalogs;

@Autowired
public void setMovieCatalogs(Set<MovieCatalog> movieCatalogs) {
this.movieCatalogs = movieCatalogs;
}

// ...
}
// Or:
public class MovieRecommender {

private Map<String, MovieCatalog> movieCatalogs;

@Autowired
public void setMovieCatalogs(Map<String, MovieCatalog> movieCatalogs) {
this.movieCatalogs = movieCatalogs;
}

// ...
}

Comments