Injecting Collections in Spring Framework Example

By | June 22, 2021

In this post, We will learn about the Injecting Collections in Spring Framework Example using a Demo Project.

Here We will learn How to  Inject List, Set, Map, Properties, and array.

We have already seen how to configure primitive data type using value attribute and object references using ref attribute of the <property> and <constructor-arg> tags in our  Spring bean configuration file. In both, cases we deal with passing a single value to a bean.

Now, what if  We want to pass more than one value like Java Collection types such as List, Set, Map, Properties and Array. To handle this situation, Spring offers the following types of collection configuration elements which are as follows −

Sr.No Element & Description
1 <list>

This helps in wiring or injecting a list of values that allows duplicates.

2 <set>

This helps in wiring a set of unique values.

3 <map>

This we use to inject a collection of key-value pairs where key and value can be of any type.

4 <props>

This also can be used to inject a collection of key-value pairs where the key and value are both Strings.

We may use either <list> or <array> to wire an array.

We may come across two situations (i) Passing direct values of the collection and (ii) Passing a reference of a bean as one of the collection elements.

Now Let’s try to understand the above concepts using the below demo Project.

pom.xml

Employee.java

Address.java

CollectionInfo.java

applicationContext.xml

ClientTest.java

If you run ClientTest.java as Java Application then it will give the below output: 

That’s all about Injecting Collections in Spring Framework Example

You May Also Like:

Spring BeanFactory Container Example
Spring ApplicationContext Container Example
Annotation-based Configuration in Spring Framework Example
Spring Java-based Configuration Example
Spring Setter Dependency Injection Example
Spring @Autowired Annotation With Setter Injection Example
Spring Constructor based Dependency Injection Example
Spring @Autowired Annotation With Constructor Injection Example
Spring Autowiring byName & byType Example
getBean() overloaded methods in Spring Framework
Spring Inner bean example
Spring Dependency Injection with Factory Method
Spring Framework @Qualifier example
Spring Bean Definition Inheritance Example
Spring bean scopes with example
Spring JSR-250 Annotations with Example
Spring BeanPostProcessor Example
Spring JDBC Integration Example
Spring JDBC Annotation Example
Spring with Jdbc java based configuration example
Spring JDBC NamedParameterJdbcTemplate Example
How to call stored procedures in the Spring Framework?

If you have any feedback or suggestion please feel free to drop in below comment box.

Leave a Reply

Your email address will not be published.