• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Spring Dependency Injection With List Collection Example

April 5, 2015 by javainterviewpoint Leave a Comment

In my previous article we have already learnt about the Dependency Injection in Spring and Setter Injection in the form of Primitives and injection in the form of Objects. Spring support injection in the form of the collection as well, it supports the below collections.

  1. List
  2. Set
  3. Map
  4. Properties

Lets take it one by one in this tutorial we will learn how to inject values to the List Collection. We will be injecting String values to a list and Objects to another list using <list> tag in our configuration file.

 <property name="stringList">
     <list>
         <value>Welcome</value>
         <value>To</value>
         <value>JavaInterivewPoint</value>
     </list>
 </property>            

When our client calls the Library class bean id “library“, the below happens which is not actually visible

List<String> list = new ArrayList<String>();
list.add("Welcome");
list.add("To");
list.add("JavaInterviewPoint");

lets see the complete example.

Folder Structure:

  1. Create a new Java Project  “SpringCoreTutorial” and create a package for our src files “com.javainterviewpoint“
  2. Add the required libraries to the build path. Java Build Path ->Libraries ->Add External JARs and add the below jars.

    commons-logging-1.1.1.jar
    spring-beans-3.2.9.RELEASE.jar
    spring-core-3.2.9.RELEASE.jar
    spring-context-3.2.9.RELEASE.jar
    spring-expression-3.2.9.RELEASE.jar

  3. Create the Java classes Book.java, Library.java and ClientLogic.java under  com.javainterviewpoint folder.
  4. Place our configuration file SpringConfig.xml in the src directory

Book.java

Book class will have all the book details such title, author, publications and its corresponding POJO’s. 

package com.javainterviewpoint;

public class Book 
{
    private String title;
    private String author;
    private String publications;
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    public String getPublications() {
        return publications;
    }
    public void setPublications(String publications) {
        this.publications = publications;
    }
}

Library.java

Library class has two Lists, stringList which holds the String values and bookList which can hold Book type of objects and its corresponding getters and setters.

package com.javainterviewpoint;

import java.util.List;

public class Library 
{
    private List stringList;
    private List bookList;
    
    public List getStringList() {
        return stringList;
    }
    public void setStringList(List stringList) {
        this.stringList = stringList;
    }
    public List getBookList() {
        return bookList;
    }
    public void setBookList(List bookList) {
        this.bookList = bookList;
    }
}

SpringConfig.xml

In our configuration file we have defined seperate id for each bean Library and Book classes. Using the <list> tag we have set values to the properties of the Library class

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

     <bean id="library" class="com.javainterviewpoint.Library">
         <property name="bookList">
             <list>
                <ref bean="book1"/>
                <ref bean="book2"/>
             </list>
         </property>
         <property name="stringList">
             <list>
                 <value>Welcome</value>
                 <value>To</value>
                 <value>JavaInterivewPoint</value>
              </list>
         </property>
    </bean>
    <bean id="book1" class="com.javainterviewpoint.Book">
       <property name="title" value="Core Spring" />
       <property name="author" value="JavaInterviewPoint" />
       <property name="publications" value="JIP" />
    </bean>
    <bean id="book2" class="com.javainterviewpoint.Book">
       <property name="title" value="Spring MVC" />
       <property name="author" value="JavaInterviewPoint" />
       <property name="publications" value="JIP" />
     </bean>
</beans>

ClientLogic.java

package com.javainterviewpoint;

import java.util.List;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class ClientLogic 
{
    public static void main(String args[])
    {
        //Read the configuration file
        Resource resource = new ClassPathResource("SpringConfig.xml");
        //Read all the bean definition
        BeanFactory bf = new XmlBeanFactory(resource);
        //Get the Library Instance
        Library library = (Library)bf.getBean("library");
        //List of Books
        List bookList = library.getBookList();
        //Lets print the properties of the Book
        for(int i=0;i<bookList.size();i++)
        {
            System.out.println("**Book"+(i+1)+" Properties**");
            Book book = bookList.get(i);
            System.out.println("Book Title        : "+book.getTitle());
            System.out.println("Book Author       : "+book.getAuthor());
            System.out.println("Book Publications : "+book.getPublications());
        }
        //Lets print the primitives
        List stringList = library.getStringList();
        System.out.println("Primitives set to List : "+stringList);
    }
}
  • Resource class reads our Configuration File(SpringConfig.xml)
  • BeanFactory class read all the bean definition mentioned in the config file.
  • Get the Library Class instance by calling the getBean() method over the bean factory.
  • As we have already injected values to both of the List of the Library class through our Config file. We will call the corresponding Lists getter to get the values associated with it.

Output

On running the ClientLogic.java we will get the below output

**Book1 Properties**
Book Title        : Core Spring
Book Author       : JavaInterviewPoint
Book Publications : JIP
**Book2 Properties**
Book Title        : Spring MVC
Book Author       : JavaInterviewPoint
Book Publications : JIP
Primitives set to List : [Welcome, To, JavaInterivewPoint]

Other interesting articles which you may like …

  • Spring Bean Scopes Example
  • Autowiring in Spring
  • Spring Autowiring byName Example
  • Spring Autowiring byType Example
  • Spring Autowiring constructor Example
  • How to Instantiate Spring IoC Container
  • How to Create and Configure Beans in the Spring IoC Container
  • Spring Constructor Injection – Resolving Ambiguity
  • How to create Spring Beans Using Spring FactoryBean
  • How to specify Spring Bean Reference and Spring Inner Bean
  • Spring Dependency Checking and Spring @Required Annotation
  • @Autowired, @Resource, @Qualifier, @Inject Annotation
  • Spring Bean Life Cycle – Bean Initialization and Destruction
  • Static Factory Method & Instance Factory Method

Filed Under: J2EE, Java, Spring, Spring Core, Spring Tutorial Tagged With: Collection, Dependency Injection, List, Spring

Leave a Reply Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·