Injecting Java Collections In Spring
By AmarSivas | | Updated : 2020-12-27 | Viewed : 87 times

In this tutorial, we will learn about injecting java collections in spring bean. So let's start looking into different types of Spring injecting Java collections using annotations.
Table of Contents:
Java List injection in Spring
We will see here List injection in spring annotations. Please have a look at the given example. Here we are taking one class which is Movies to print the list of movies. But the list is here injected list. So we will see how to inject it.
public class Movies {
@Autowired
private List<String> movieList;
}
Here we have a
@Configuration
public class AppConfig {
@Bean
public Movies getMovies() {
return new Movies();
}
@Bean
public List<String> movieList() {
return Arrays.asList("Iron Man", "Spider Man", "Thor");
}
}
So
Java Set injection in Spring
Now we will learn to know how to
public class Movies {
@Autowired
private Set<String> moviesSet;
public Movies() {
}
}
And now
@Configuration
public class AppConfig {
@Bean
public Movies getMovies() {
return new Movies();
}
@Bean
public Set<String> moviesSet() {
Set moviesSet = new HashSet<>();
//.. add the movies here
return moviesSet;
}
}
So Set of Movies and Movies beans will be created. As per the definition of the Movies class, the Set of Movies will be injected when Movies object initiated.
Java Map injection in Spring
So for injection of the
public class Movies {
@Autowired
private Map<String, String> heroMovieMap;
public Movies() {
}
}
@Configuration
public class AppConfig {
@Bean
public Movies getMovies() {
return new Movies();
}
@Bean
public Map<String, String> heroMovieMap() {
Map heroMovieMap = new HashMap();
//..add here hero and Movie entries here
return heroMovieMap;
}
}
Spring Bean injection in Spring
So far we looked at how to inject collection class injection into the Spring bean or other class. Now we will look into the injection of Actor class into the Movie class by using the Hero Spring bean reference.
Please look at the Actor and Movies class as given below.
@Getter
public class Actor {
private String actorName;
}
@Getter
public class Movie {
@Autowired
private List<Actor> actorList;
}
@Configuration
public class AppConfig {
@Bean
public Actor getActor1() {
return new Actor("Hero");
}
@Bean
public Actor getActor2() {
return new Actor("Heroine");
}
@Bean
public Movie getMovie() {
return new Movie("Movie");
}
}
Here in
Properties injection in Spring
One new
In
@Getter
public class Movie {
@Value("${test.movie.name}")
private String movieName;
}
@Configuration
@PropertySource("classpath:test.properties")
public class AppConfig {
@Bean
public Movie getASpringBean() {
return new Movie();
}
}
Here we used the
The code repository for this article is in Github. Please look at Spring-Injecting-Collections-Example-App