Spring Constructor Injection With List
In spring we can inject values to Collection by constructor
injection. We can use three elements in <constructor-arg> element, it can be list, set and map etc.
In this example we are going to use list to store Players
batting style, bowling style and nick name.
Info : list can contain duplicate elements.
Players.java
package com.TheTechMatin.Entity;
import java.util.List;
public class Players {
private String fullName;
private String role;
private String board;
private List<String> playersInfo;
public Players() {
}
public Players(String fullName, String role, String
board, List<String> playersInfo) {
this.fullName = fullName;
this.role = role;
this.board = board;
this.playersInfo = playersInfo;
}
@Override
public String toString() {
return "Players [fullName=" + fullName + ", role=" + role + ", board=" + board + ",
playersInfo=" + playersInfo
+ "]";
}
}
The <list>
element of <constructor-arg> is used here to define the list.
applicationContext.xml
<?xml version="1.0"
encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="player"
class="com.TheTechMatin.Entity.Players">
<constructor-arg value="Sir Ravindra
Jadeja"></constructor-arg>
<constructor-arg value="All
Rounder"></constructor-arg>
<constructor-arg value="BCCI"></constructor-arg>
<constructor-arg>
<list>
<!--
batting style -->
<value>Left Hand Batting</value>
<!-- bowling style -->
<value>Left Hand Bowling</value>
<!-- nick name -->
<value>Jaddu</value>
</list>
</constructor-arg>
</bean>
</beans>
This is the main class in which first loading config file then getting bean from it.
TestApp.java
package com.TheTechMatin.Entity;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestApp {
public static void main(String[] args) {
//load the
configuration file
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//just
printing the message
System.out.println("Hello Welcome To Sping Constructor Injection!");
//get the
bean
Players player = context.getBean(Players.class);
//print the
Players class
System.out.println(player);
//close the
context
context.close();
}
}
On
execution of TestApp.java class the following output will be displayed on console.
Hello
Welcome To Sping Constructor Injection!
Players
[fullName=Sir Ravindra Jadeja, role=All Rounder, board=BCCI, playersInfo=[Left
Hand Batting, Left Hand Bowling, Jaddu]]
Tested
On Eclipse 2019-06
No comments