How to inject Collection in Spring

Spring supports us the way to inject Collection with type: List, Set, Map and Properties. So we can pass a bundle of direct data values or reference of beans to Collection Objects.

The tutorial shows you how to use XML configuration to do those things.

Related Post:
How to use Spring Factory Method to create Spring Bean

I. Demo Video
II. Technology

– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE
– Spring Boot: 1.4.0.RELEASE

III. Overview
1. Goal

To build an application that runs with bean customerService of class CustomerService which has many members under Collection Types: List, Set, Map, Properties (with primitive datatype and Java Class Objects):
injectcollection-bean-goal

2. Project Structure

injectcollections-projectstructure

3. Step to do

– Create Spring Boot project
– Create DataModels
– Create a Service
– Create Spring Bean Configuration File
– Create a Web Controller
– Run Spring Boot Application & Enjoy Result

IV. Practice
1. Create Spring Boot project

– Open Spring Tool Suite, on Menu, choose File -> New -> Spring Starter Project, then fill each fields:
injectcollection-startproject

Click Next, in Web: choose Web:
springaop-aspectj-configweb

Click Finish. Spring Boot project will be created successfully.

2. Create DataModels

Under package model, create class Customer and BilingualCustomer.java:

Content of Bilingual.java:

3. Create a Service

Under package service, create class CustomerService.

Content of CustomerService.java:

4. Create Spring Bean Configuration File

Under src/main/resources, create bean.xml:

5. Create a WebController

Under package controller, create class WebController.

WebController.java:

6. Run Spring Boot Application & Enjoy Result

– Config maven build:
clean install
– Run project with mode Spring Boot App
– Check results:

Request 1
http://localhost:8080/set
injectcollection-req1

Request 2
http://localhost:8080/map
injectcollection-req2

Request 3
http://localhost:8080/list
injectcollection-req3

Request 4
http://localhost:8080/prop
injectcollection-req4

V. Source Code

SpringInjectCollections


Related Posts



    Got Something To Say:

    Your email address will not be published. Required fields are marked *

    *