Home Spring Framework Spring - Injecting Collections

Spring – Injecting Collections

Spring Framework supports injecting Java Collection types. In this tutorial we will see how to inject Arrays, List, Set and Map with examples.

1. Inject array with @Autowired

Let’s create an array bean which provides person names. In following example, we have defined namesArray to hold person names as String array. Let’s declare Spring @Autowired on namesArray for field injection.

public class CollectionTestBean {

        // ....

	@Autowired
	private String[] namesArray;

	public void printNamesArry() {
		System.out.println("printNamesArray:"+Arrays.asList(namesArray));
	}
}

Before we inject namesArray, it should be register in the configuration. We also configured CollectionTestBean, because Spring allow to inject beans only within Spring beans or components.

@Configuration
public class CollectionBeanConfig {

	@Bean
	public CollectionTestBean getCollectionTestBean() {
		return new CollectionTestBean();
	}

	@Bean
	public String[] namesArray() {
		return new String[] {"Peter", "John", "Anand", "Gerhard"};
	}

       // ...
}

Let’s test the configuration.

public class ApplicationCollectionDemo {
	
	public static void main(String[] args) {
		
		ApplicationContext ctxt = new AnnotationConfigApplicationContext(CollectionBeanConfig.class, FruitConfig.class);
		CollectionTestBean collectionTestBean = ctxt.getBean(CollectionTestBean.class);

		collectionTestBean.printNamesArry();
                // ...
	}
}

Output:

printNamesArray:[Peter, John, Anand, Gerhard]

2. Injecting Set with @Autowired

Same like arrays we can inject java.util.List, java.util.Set, java.util.Map. Let’s see autowiring Set.

public class CollectionTestBean {

	@Autowired
	private Set<String> namesSet;

	public void printNamesSet() {
		System.out.println("printNamesSet:"+namesSet);
	}

	// ...
}

Registering bean for namesSet in configuration.

@Configuration
public class CollectionBeanConfig {
	
	// Unmodifiable set
	@Bean
	public Set<String> namesSet() {
		return Set.of("Peter", "John", "Anand", "Gerhard");
	}
	
	// ...

}

Testing the configuration.

public class ApplicationCollectionDemo {
	
	public static void main(String[] args) {
		
		ApplicationContext ctxt = new AnnotationConfigApplicationContext(CollectionBeanConfig.class, FruitConfig.class);
		CollectionTestBean collectionTestBean = ctxt.getBean(CollectionTestBean.class);
		
		collectionTestBean.printNamesSet();
		
                // ...
	}
}

Output:

printNamesSet:[Anand, John, Peter, Gerhard]

3. Injecting List using Constructor

This time let’s see how to inject List using constructor.

public class CollectionTestBean {

	private List<String> namesList;

	public CollectionTestBean(List<String> namesList) {
		this.namesList = namesList;
	}

	public void printList() {
		System.out.println("printList:"+namesList);
	}
	
	// ...
}

Bean configuration for namesList.

@Configuration
public class CollectionBeanConfig {
	
	@Bean
	public CollectionTestBean getCollectionTestBean() {
		return new CollectionTestBean(Arrays.asList("Peter", "John", "Anand", "Gerhard"););
	}
	
	// ...
}

Invoking printList() will get following results.

printList:[Peter, John, Anand, Gerhard]

4. Injecting Map with Setter method

In this case let’s inject java.util.Map using setter method.

public class CollectionTestBean {

	private Map<Integer, String> namesMap;

	@Autowired
	public void setNamesMap(Map<Integer, String> namesMap) {
		this.namesMap = namesMap;
	}

	public void printNamesMap() {
		System.out.println("printNamesMap:"+namesMap);
	}

	// ...
}

Configuring bean for namesMap.

@Configuration
public class CollectionBeanConfig {
	
	@Bean
	public Map<Integer, String> namesMap() {
		Map<Integer, String> map = new HashMap<>();
		map.put(1, "Peter");
		map.put(2, "John");
		map.put(3, "Anand");
		map.put(4, "Gerhard");
		
		return map;
	}
	
	// ...
}

Test results on invoking printNamesMap().

printNamesMap:{1=Peter, 2=John, 3=Anand, 4=Gerhard}

5. Injecting Components as List

Let’s create an interface Fruit, and Apple, Mango, Orange a Banana are the implementation classes of Fruit interface and make them spring components.

public interface Fruit {
	
}
@Component
public class Apple implements Fruit {

	@Override
	public String toString() {
		return "Apple";
	}
}

@Component
public class Banana implements Fruit {

	@Override
	public String toString() {
		return "Banana";
	}
}

@Component
public class Mango implements Fruit {

	@Override
	public String toString() {
		return "Mango";
	}
}

@Component
public class Orange implements Fruit {

	@Override
	public String toString() {
		return "Orange";
	}
}

If an interface injected with @Autowired (in this example List<Fruit>), all the implementation classes will be injected to list.

public class CollectionTestBean {
       
	@Autowired
	private List<Fruit> fruitList;

	public void printFruitList() {
		System.out.println("printFruitList:"+fruitList);
	}

	// ...

}

Results when invoke printFruitList():

printFruitList:[Apple, Banana, Mango, Orange]

6. Injecting Bean references as collection

Spring allows to create multiple beans of same class and inject all of them to a collection. Let’s look into an example.

public class Animal {

	private String name;

	public Animal(String name) {
		this.name = name;
	}
	
	@Override
	public String toString() {
		return name;
	}
}

Create multiple beans of Animal type.

@Configuration
public class CollectionBeanConfig {
	
	// ...
	
	@Bean
	public Animal getTiger() {
		return new Animal("Tiger");
	}
	
	@Bean
	public Animal getDeer() {
		return new Animal("Deer");
	}
	
	@Bean
	public Animal getKangaroo() {
		return new Animal("Kangaroo");
	}
	
	@Bean
	public Animal getFox() {
		return new Animal("Fox");
	}
}
public class CollectionTestBean {

	@Autowired
	private List<Animal> animalList;

	public void printAnimalList() {
		System.out.println("printAnimalList:"+animalList);
	}

	// ...

}

Results when invoke printAnimalList():

printAnimalList:[Tiger, Deer, Kangaroo, Fox]

7. Injecting List of beans using @Qualifier

Spring allows us to inject specific beans to collection using @Qualifier. For example, in above example only if you wants to inject non ferocious animals to list:

@Configuration
public class CollectionBeanConfig {
	
	// ...
	
	@Bean
	public Animal getTiger() {
		return new Animal("Tiger");
	}
	
	@Bean
	@Qualifier("nonFerciousAnimals")
	public Animal getDeer() {
		return new Animal("Deer");
	}
	
	@Bean
	@Qualifier("nonFerciousAnimals")
	public Animal getKangaroo() {
		return new Animal("Kangaroo");
	}
	
	@Bean
	public Animal getFox() {
		return new Animal("Fox");
	}
}

Injecting nonferocious Animal beans to List.

public class CollectionTestBean {

	@Autowired
	@Qualifier("nonFerciousAnimals")
	private List<Animal> nonFerciousAnimals;

	public void printNoFerociousAnimalList() {
		System.out.println("printNoFerociousAnimalList:"+nonFerciousAnimals);
	}

	// ...
}

Results when invoke printNoFerociousAnimalList():

printNoFerociousAnimalList:[Deer, Kangaroo]

8. Sort the Injecting order of beans in List

We can control the order of injecting beans to List using Spring’s @Order. The lowest number will get highest order in List.

@Configuration
public class CollectionBeanConfig {
	
	// ...
	
	@Bean
	public Animal getTiger() {
		return new Animal("Tiger");
	}
	
	@Bean
	@Order(1)
	@Qualifier("nonFerciousAnimals")
	public Animal getDeer() {
		return new Animal("Deer");
	}
	
	@Bean
	@Qualifier("nonFerciousAnimals")
	public Animal getKangaroo() {
		return new Animal("Kangaroo");
	}
	
	@Bean
	@Order(2)
	public Animal getFox() {
		return new Animal("Fox");
	}
}
public class CollectionTestBean {

	@Autowired
	private List<Animal> animalList;

	public void printAnimalList() {
		System.out.println("printAnimalList:"+animalList);
	}

	// ...

}

Output reults:

printAnimalList:[Deer, Fox, Tiger, Kangaroo]

9. Conclusion

In this tutorial we have covered how to autowire beans and components to a collection using @Autowired in Spring Framework. Also we have seen injection with sort order, reference types and selecting specific beans to a collection.

Other Related Tutorials:

  1. Spring @Order
  2. Spring @Lazy
  3. Spring @Autowired
  4. Spring Boot XML Beans
  5. Spring @Primary
  6. Spring @Import
  7. Spring Component Scanning
  8. Spring @ComponentScan Filter Types

LEAVE A REPLY

Please enter your comment!
Please enter your name here