Wednesday, May 27, 2015

Constructor injection and Setter injection in Spring Examples



Dependency Injection by Constructor Example
1.     Dependency Injection by constructor
2.     Injecting primitive and string-based values
We can inject the dependency by constructor. The <constructor-arg> sub element of <bean> is used for constructor injection. Here we are going to inject
1.     primitive and String-based values
2.     Dependent object (contained object)
3.     Collection values etc.
Injecting primitive and string-based values
Let's see the simple example to inject primitive and string-based values. We have created three files here:
  • Employee.java
  • applicationContext.xml
  • Test.java
Employee.java
It is a simple class containing two fields id and name. There are four constructors and one method in this class.
package com.mycompany;    
public class Employee {  
private int id;  
private String name;  
  public Employee() {System.out.println("def cons");}  
  public Employee(int id) {this.id = id;}  
  public Employee(String name) {  this.name = name;}  
  public Employee(int id, String name) {  
    this.id = id;  
    this.name = name;  
}    void show(){  
    System.out.println(id+" "+name);  
}  
}  
applicationContext.xml
We are providing the information into the bean by this file. The constructor-arg element invokes the constructor. In such case, parameterized constructor of int type will be invoked. The value attribute of constructor-arg element will assign the specified value. The type attribute specifies that int parameter constructor will be invoked.
<?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="e" class="com.mycompany.Employee">  
<constructor-arg value="10" type="int"></constructor-arg>  
</bean>  
</beans>  
Test.java
This class gets the bean from the applicationContext.xml file and calls the show method.
package com.mycompany;  
import org.springframework.beans.factory.BeanFactory;  
import org.springframework.beans.factory.xml.XmlBeanFactory;  
import org.springframework.core.io.*;  
  
public class Test {  
    public static void main(String[] args) {  
        Resource r=new ClassPathResource("applicationContext.xml");  
        BeanFactory factory=new XmlBeanFactory(r);  
          
        Employee s=(Employee)factory.getBean("e");  
        s.show();  
          
    }  
}  
Output: 10 null
Injecting string-based values
If you don't specify the type attribute in the constructor-arg element, by default string type constructor will be invoked. 
<bean id="e" class="com.mycompany.Employee">  
<constructor-arg value="10"></constructor-arg>  
</bean>  
  If you change the bean element as given above, string parameter constructor will be invoked and the output will be 0 10.
Output: 0 10
You may also pass the string literal as following:
<bean id="e" class="com.mycompany.Employee">  
<constructor-arg value="Sonoo"></constructor-arg>  
</bean>  
Output: 0 Sonoo
You may pass integer literal and string both as following  
<bean id="e" class="com.mycompany.Employee">  
<constructor-arg value="10" type="int" ></constructor-arg>  
<constructor-arg value="Sonoo"></constructor-arg>  
</bean>  

Constructor Injection with Dependent Object
1.    Constructor Injection with Dependent Object

If there is HAS-A relationship between the classes, we create the instance of dependent object (contained object) first then pass it as an argument of the main class constructor. Here, our scenario is Employee HAS-A Address. The Address class object will be termed as the dependent object. Let's see the Address class first:
Address.java
This class contains three properties, one constructor and toString() method to return the values of these object.
package com.mycompany;
    public class Address {
private String city;
private String state;
private String country;

public Address(String city, String state, String country) {
super();
this.city = city;
this.state = state;
this.country = country;
}

public String toString(){
return city+" "+state+" "+country;
}
}
Employee.java
It contains three properties id, name and address(dependent object) ,two constructors and show() method to show the records of the current object including the depedent object.
package com.mycompany;

public class Employee {
private int id;
private String name;
private Address address;//Aggregation

public Employee() {System.out.println("def cons");}

public Employee(int id, String name, Address address) {
super();
this.id = id;
this.name = name;
this.address = address;
}

void show(){
System.out.println(id+" "+name);
System.out.println(address.toString());
}

}
applicationContext.xml
The ref attribute is used to define the reference of another object, such way we are passing the dependent object as an constructor argument.
<?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-beans3.0.xsd">

<bean id="a1" class="com.mycompany.Address">
<constructor-arg value="ghaziabad"></constructor-arg>
<constructor-arg value="UP"></constructor-arg>
<constructor-arg value="India"></constructor-arg>
</bean> 
<bean id="e" class="com.mycompany.Employee">
<constructor-arg value="12" type="int"></constructor-arg>
<constructor-arg value="Sonoo"></constructor-arg>
<constructor-arg>
<ref bean="a1"/>
</constructor-arg>
</bean>
</beans>
Test.java
This class gets the bean from the applicationContext.xml file and calls the show method.
package com.mycompany;

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

public class Test {
public static void main(String[] args) {

Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);

Employee s=(Employee)factory.getBean("e");
s.show();

}
}
Constructor Injection with Collection Example
1.    Constructor Injection with Collection
We can inject collection values by constructor in spring framework. There can be used three elements inside the constructor-arg element.
It can be: 1 .list 2.set 3.map
Each collection can have string based and non-string based values.
In this example, we are taking the example of Forum where One question can have multiple answers. There are three pages:
1.    Question.java
2.    applicationContext.xml
3.    Test.java
In this example, we are using list that can have duplicate elements, you may use set that have only unique elements. But, you need to change list to set in the applicationContext.xml file and List to Set in the Question.java file.
Question.java
This class contains three properties, two constructors and displayInfo() method that prints the information. Here, we are using List to contain the multiple answers.
package com.mycompany;  
  
import java.util.Iterator;  
import java.util.List;  

public class Question {  
private int id;  
private String name;  
private List<String> answers;  
  
public Question() {}  
public Question(int id, String name, List<String> answers) {  
    super();  
    this.id = id;  
    this.name = name;  
    this.answers = answers;  
}  
  
public void displayInfo(){  
    System.out.println(id+" "+name);  
    System.out.println("answers are:");  
    Iterator<String> itr=answers.iterator();  
    while(itr.hasNext()){  
        System.out.println(itr.next());  
    }  
}  
  
}  
applicationContext.xml
The list element of constructor-arg is used here to define the list.
<?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="q" class="com.mycompany.Question">  
<constructor-arg value="111"></constructor-arg>  
<constructor-arg value="What is java?"></constructor-arg>  
<constructor-arg>  
<list>  
<value>Java is a programming language</value>  
<value>Java is a Platform</value>  
<value>Java is an Island of Indonasia</value>  
</list>  
</constructor-arg>  
</bean>  
  
</beans>  
Test.java
This class gets the bean from the applicationContext.xml file and calls the displayInfo method.
package com.mycompany;  
  
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 Test {  
public static void main(String[] args) {  
    Resource r=new ClassPathResource("applicationContext.xml");  
    BeanFactory factory=new XmlBeanFactory(r);  
      
    Question q=(Question)factory.getBean("q");  
    q.displayInfo();  
      
}  
}

Constructor Injection with Non-String Collection (having Dependent Object) Example
If we have dependent object in the collection, we can inject these information by using the ref element inside the listset or map.
In this example, we are taking the example of Forum where One question can have multiple answers. But Answer has its own information such as answerId, answer and postedBy. There are four pages used in this example:
1.   Question.java
2.   Answer.java
3.   applicationContext.xml
4.   Test.java
In this example, we are using list that can have duplicate elements, you may use set that have only unique elements. But, you need to change list to set in the applicationContext.xml file and List to Set in the Question.java file.
Question.java
This class contains three properties, two constructors and displayInfo() method that prints the information. Here, we are using List to contain the multiple answers.
package com.mycompany;

import java.util.Iterator;
import java.util.List;

public class Question {
private int id;
private String name;
private List<Answer> answers;

public Question() {}
public Question(int id, String name, List<Answer> answers) {
super();
this.id = id;
this.name = name;
this.answers = answers;
}

public void displayInfo(){
System.out.println(id+" "+name);
System.out.println("answers are:");
Iterator<Answer> itr=answers.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}

}  Answer.java
This class has three properties id, name and by with constructor and toString() method.
package com.mycompany;

public class Answer {
private int id;
private String name;
private String by;

public Answer() {}
public Answer(int id, String name, String by) {
super();
this.id = id;
this.name = name;
this.by = by;
}

public String toString(){
return id+" "+name+" "+by;
}
}
applicationContext.xml
The ref element is used to define the reference of another bean. Here, we are using bean attribute of ref element to specify the reference of another bean.
<?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="ans1" class="com.mycompany.Answer">
<constructor-arg value="1"></constructor-arg>
<constructor-arg value="Java is a programming language"></constructor-arg>
<constructor-arg value="John"></constructor-arg>
</bean>

<bean id="ans2" class="com.mycompany.Answer">
<constructor-arg value="2"></constructor-arg>
<constructor-arg value="Java is a Platform"></constructor-arg>
<constructor-arg value="Ravi"></constructor-arg>
</bean>

<bean id="q" class="com.mycompany.Question">
<constructor-arg value="111"></constructor-arg>
<constructor-arg value="What is java?"></constructor-arg>
<constructor-arg>
<list>
<ref bean="ans1"/>
<ref bean="ans2"/>
</list>
</constructor-arg>
</bean>

</beans>
Test.java
This class gets the bean from the applicationContext.xml file and calls the displayInfo method.
package com.mycompany;

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 Test {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);

Question q=(Question)factory.getBean("q");
q.displayInfo();

}
}


Constructor Injection with Map Example:
In this example, we are using map as the answer that have answer with posted username. Here, we are using key and value pair both as a string.
Like previous examples, it is the example of forum where one question can have multiple answers.
Question.java
This class contains three properties, two constructors and displayInfo () method to display the information.
package com.mycompany;  
import java.util.Iterator;  
import java.util.Map;  
import java.util.Set;  
import java.util.Map.Entry;  
  
public class Question {  
private int id;  
private String name;  
private Map<String,String> answers;  
  
public Question() {}  
public Question(int id, String name, Map<String, String> answers) {  
    super();  
    this.id = id;  
    this.name = name;  
    this.answers = answers;  
}  
  
public void displayInfo(){  
    System.out.println("question id:"+id);  
    System.out.println("question name:"+name);  
    System.out.println("Answers....");  
    Set<Entry<String, String>> set=answers.entrySet();  
    Iterator<Entry<String, String>> itr=set.iterator();  
    while(itr.hasNext()){  
        Entry<String,String> entry=itr.next();  
        System.out.println("Answer:"+entry.getKey()+" Posted By:"+entry.getValue());  
    }  
}  
}  applicationContext.xml
The entry attribute of map is used to define the key and value information.
<?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="q" class="com.mycompany.Question">  
<constructor-arg value="11"></constructor-arg>  
<constructor-arg value="What is Java?"></constructor-arg>  
<constructor-arg>  
<map>  
<entry key="Java is a Programming Language"  value="Ajay Kumar"></entry>  
<entry key="Java is a Platform" value="John Smith"></entry>  
<entry key="Java is an Island" value="Raj Kumar"></entry>  
</map>  
</constructor-arg>  
</bean>  
  
</beans> 
 Test.java
This classgets the bean from the applicationContext.xml file and calls the displayInfo() method.
package com.mycompany;  
  
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 Test {  
public static void main(String[] args) {  
    Resource r=new ClassPathResource("applicationContext.xml");  
    BeanFactory factory=new XmlBeanFactory(r);  
      
    Question q=(Question)factory.getBean("q");  
    q.displayInfo();  
      
}  
}  


Constructor Injection with Non-String Map (having dependent Object) Example
In this example, we are using map as the answer that have Answer and User. Here, we are using key and value pair both as an object. Answer has its own information such as answerId, answer and postedDate, User has its own information such as userId, username, emailId.
Like previous examples, it is the example of forum where one question can have multiple answers.
Question.java
This class contains three properties, two constructors and displayInfo() method to display the information.
package com.mycompany;  
import java.util.Iterator;  
import java.util.Map;  
import java.util.Set;  
import java.util.Map.Entry;  
  
public class Question {  
private int id;  
private String name;  
private Map<Answer,User> answers;  
  
public Question() {}  
public Question(int id, String name, Map<Answer, User> answers) {  
    super();  
    this.id = id;  
    this.name = name;  
    this.answers = answers;  
}  
  
  
public void displayInfo(){  
    System.out.println("question id:"+id);  
    System.out.println("question name:"+name);  
    System.out.println("Answers....");  
    Set<Entry<Answer, User>> set=answers.entrySet();  
    Iterator<Entry<Answer, User>> itr=set.iterator();  
    while(itr.hasNext()){  
        Entry<Answer, User> entry=itr.next();  
        Answer ans=entry.getKey();  
        User user=entry.getValue();  
        System.out.println("Answer Information:");  
        System.out.println(ans);  
        System.out.println("Posted By:");  
        System.out.println(user);  
    }  
}  
}  
Answer.java
package com.mycompany;  
  
import java.util.Date;  
  
public class Answer {  
private int id;  
private String answer;  
private Date postedDate;  
public Answer() {}  
public Answer(int id, String answer, Date postedDate) {  
    super();  
    this.id = id;  
    this.answer = answer;  
    this.postedDate = postedDate;  
}  
  
public String toString(){  
    return "Id:"+id+" Answer:"+answer+" Posted Date:"+postedDate;  
}  
}  
User.java
package com.mycompany;  
  
public class User {  
private int id;  
private String name,email;  
public User() {}  
public User(int id, String name, String email) {  
    super();  
    this.id = id;  
    this.name = name;  
    this.email = email;  
}  
  
public String toString(){  
    return "Id:"+id+" Name:"+name+" Email Id:"+email;  
}  
 applicationContext.xml
The key-ref and value-ref attributes of entry element is used to define the reference of bean in the map.
<?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="answer1" class="com.mycompany.Answer">  
<constructor-arg value="1"></constructor-arg>  
<constructor-arg value="Java is a Programming Language"></constructor-arg>  
<constructor-arg value="12/12/2001"></constructor-arg>  
</bean>  
<bean id="answer2" class="com.mycompany.Answer">  
<constructor-arg value="2"></constructor-arg>  
<constructor-arg value="Java is a Platform"></constructor-arg>  
<constructor-arg value="12/12/2003"></constructor-arg>  
</bean>  
  
<bean id="user1" class="com.mycompany.User">  
<constructor-arg value="1"></constructor-arg>  
<constructor-arg value="Arun Kumar"></constructor-arg>  
<constructor-arg value="arun@gmail.com"></constructor-arg>  
</bean>  
<bean id="user2" class="com.mycompany.User">  
<constructor-arg value="2"></constructor-arg>  
<constructor-arg value="Varun Kumar"></constructor-arg>  
<constructor-arg value="Varun@gmail.com"></constructor-arg>  
</bean>  
  
<bean id="q" class="com.mycompany.Question">  
<constructor-arg value="1"></constructor-arg>  
<constructor-arg value="What is Java?"></constructor-arg>  
<constructor-arg>  
<map>  
<entry key-ref="answer1" value-ref="user1"></entry>  
<entry key-ref="answer2" value-ref="user2"></entry>  
</map>  
</constructor-arg>  
</bean>  
  
</beans>  
Test.java
This class gets the bean from the applicationContext.xml file and calls the displayInfo() method to display the information.
package com.mycompany;  
  
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 Test {  
public static void main(String[] args) {  
    Resource r=new ClassPathResource("applicationContext.xml");  
    BeanFactory factory=new XmlBeanFactory(r);  
      
    Question q=(Question)factory.getBean("q");  
    q.displayInfo();  
      
}  
}  
Inheriting Bean in Spring
By using the parent attribute of bean, we can specify the inheritance relation between the beans. In such case, parent bean values will be inherited to the current bean.
Let's see the simple example to inherit the bean.
Employee.java
This class contains three properties, three constructor and show() method to display the values.
package com.mycompany;  
  
public class Employee {  
private int id;  
private String name;  
private Address address;  
public Employee() {}  
  
public Employee(int id, String name) {  
    super();  
    this.id = id;  
    this.name = name;  
}  
public Employee(int id, String name, Address address) {  
    super();  
    this.id = id;  
    this.name = name;  
    this.address = address;  
}  
  
void show(){  
    System.out.println(id+" "+name);  
    System.out.println(address);  
}  
  
}  
Answer.java
package com.mycompany;  
  
public class Address {  
private String addressLine1,city,state,country;  
  
public Address(String addressLine1, String city, String state, String country) {  
    super();  
    this.addressLine1 = addressLine1;  
    this.city = city;  
    this.state = state;  
    this.country = country;  
}  
public String toString(){  
    return addressLine1+" "+city+" "+state+" "+country;  
}  
  
}  
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="e1" class="com.mycompany.Employee">  
<constructor-arg value="101"></constructor-arg>  
<constructor-arg  value="Sachin"></constructor-arg>  
</bean>  
  
<bean id="address1" class="com.mycompany.Address">  
<constructor-arg value="21,Lohianagar"></constructor-arg>  
<constructor-arg value="Ghaziabad"></constructor-arg>  
<constructor-arg value="UP"></constructor-arg>  
<constructor-arg value="USA"></constructor-arg>  
</bean>  
  
<bean id="e2" class="com.mycompany.Employee" parent="e1">  
<constructor-arg ref="address1"></constructor-arg>  
</bean>  
  
</beans>  
Test.java
This class gets the bean from the applicationContext.xml file and calls the show method.
package com.mycompany;  
  
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 Test {  
public static void main(String[] args) {  
    Resource r=new ClassPathResource("applicationContext.xml");  
    BeanFactory factory=new XmlBeanFactory(r);  
      
    Employee e1=(Employee)factory.getBean("e2");  
    e1.show();  
      
}  
}  
Dependency Injection by setter method
We can inject the dependency by setter method also. The<property> subelement of <bean> is used for setter injection. Here we are going to inject
  1. primitive and String-based values
  2. Dependent object (contained object)
  3. Collection values etc.
Injecting primitive and string-based values by setter method
Let's see the simple example to inject primitive and string-based values by setter method. We have created three files here:
  • Employee.java
  • applicationContext.xml
  • Test.java
Employee.java
It is a simple class containing three fields id, name and city with its setters and getters and a method to display these informations.
package com.mycompany;  
  
public class Employee {  
private int id;  
private String name;  
private String city;  
  
public int getId() {  
    return id;  
}  
public void setId(int id) {  
    this.id = id;  
}  
public String getName() {  
    return name;  
}  
public void setName(String name) {  
    this.name = name;  
}  
  
public String getCity() {  
    return city;  
}  
public void setCity(String city) {  
    this.city = city;  
}  
void display(){  
    System.out.println(id+" "+name+" "+city);  
}  
  
}
  applicationContext.xml
These are providing the information into the bean by this file. The property element invokes the setter method. The value subelement of property will assign the specified value.
<?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="obj" class="com.mycompany.Employee">  
<property name="id">  
<value>20</value>  
</property>  
<property name="name">  
<value>Arun</value>  
</property>  
<property name="city">  
<value>ghaziabad</value>  
</property>  
  
</bean>  
</beans>  
Test.java
This class gets the bean from the applicationContext.xml file and calls the display method.
package com.mycompany;  
  
import org.springframework.beans.factory.BeanFactory;  
import org.springframework.beans.factory.xml.XmlBeanFactory;  
import org.springframework.core.io.*;  
  
public class Test {  
    public static void main(String[] args) {  
          
        Resource r=new ClassPathResource("applicationContext.xml");  
        BeanFactory factory=new XmlBeanFactory(r);  
          
        Employee e=(Employee)factory.getBean("obj");  
        s.display();  
          
    }  
}  
Output: 20 Arun ghaziabad

Setter Injection with Dependent Object Example
Like Constructor Injection, we can inject the dependency of another bean using setters. In such case, we use property element. Here, our scenario is Employee HAS-A Address. The Address class object will be termed as the dependent object. Let's see the Address class first:
Address.java
This class contains four properties, setters and getters and toString() method.
package com.mycompany;  
  
public class Address {  
private String addressLine1,city,state,country;  
  
//getters and setters  
  
public String toString(){  
    return addressLine1+" "+city+" "+state+" "+country;  
}  Employee.java
It contains three properties id, name and address(dependent object) , setters and setters with displayInfo() method.
package com.mycompany;  
  
public class Employee {  
private int id;  
private String name;  
private Address address;  
  
//setters and getters  
  
void displayInfo(){  
    System.out.println(id+" "+name);  
    System.out.println(address);  
}  
 applicationContext.xml
The ref attribute of property elements is used to define the reference of another bean.
<?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="address1" class="com.mycompany.Address">  
<property name="addressLine1" value="51,Lohianagar"></property>  
<property name="city" value="Ghaziabad"></property>  
<property name="state" value="UP"></property>  
<property name="country" value="India"></property>  
</bean>  
  
<bean id="obj" class="com.mycompany.Employee">  
<property name="id" value="1"></property>  
<property name="name" value="Sachin Yadav"></property>  
<property name="address" ref="address1"></property>  
</bean>  
  
</beans>  
Test.java
This class gets the bean from the applicationContext.xml file and calls the displayInfo() method.
package com.mycompany;  
  
import org.springframework.beans.factory.BeanFactory;  
import org.springframework.beans.factory.xml.XmlBeanFactory;  
import org.springframework.context.ApplicationContext;  
import org.springframework.context.support.ClassPathXmlApplicationContext;  
import org.springframework.core.io.ClassPathResource;  
import org.springframework.core.io.Resource;  
  
public class Test {  
public static void main(String[] args) {  
    Resource r=new ClassPathResource("applicationContext.xml");  
    BeanFactory factory=new XmlBeanFactory(r);  
      
    Employee e=(Employee)factory.getBean("obj");  
    e.displayInfo();  
      
}  
}  
Setter Injection with Collection Example
We can inject collection values by setter method in spring framework. There can be used three elements inside the property element.
It can be: 1. list  2. Set  3 . map
Each collection can have string based and non-string based values.
In this example, we are taking the example of Forum where One question can have multiple answers. There are three pages:
  1. Question.java
  2. applicationContext.xml
  3. Test.java
In this example, we are using list that can have duplicate elements, you may use set that have only unique elements. But, you need to change list to set in the applicationContext.xml file and List to Set in the Question.java file.
Question.java
This class contains three properties with setters and getters and displayInfo() method that prints the information. Here, we are using List to contain the multiple answers.
package com.mycompany;  
import java.util.Iterator;  
import java.util.List;  
  
public class Question {  
private int id;  
private String name;  
private List<String> answers;  
  
//setters and getters  
  
public void displayInfo(){  
    System.out.println(id+" "+name);  
    System.out.println("answers are:");  
    Iterator<String> itr=answers.iterator();  
    while(itr.hasNext()){  
        System.out.println(itr.next());  
    }  
}  
  
}  
applicationContext.xml
The list element of constructor-arg is used here to define the list.
<?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="q" class="com.mycompany.Question">  
<property name="id" value="1"></property>  
<property name="name" value="What is Java?"></property>  
<property name="answers">  
<list>  
<value>Java is a programming language</value>  
<value>Java is a platform</value>  
<value>Java is an Island</value>  
</list>  
</property>  
</bean>  
  
</beans> 
 Test.java
This class gets the bean from the applicationContext.xml file and calls the displayInfo method.
package com.mycompany;  
  
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 Test {  
public static void main(String[] args) {  
    Resource r=new ClassPathResource("applicationContext.xml");  
    BeanFactory factory=new XmlBeanFactory(r);  
      
    Question q=(Question)factory.getBean("q");  
    q.displayInfo();  
      
}  
}  
Setter Injection with Non-String Collection (having Dependent Object) Example
If we have dependent object in the collection, we can inject these information by using the ref element inside the listset or map. Here, we will use list, set or map element inside the property element.
In this example, we are taking the example of Forum where One question can have multiple answers. But Answer has its own information such as answerId, answer and postedBy. There are four pages used in this example:
  1. Question.java
  2. Answer.java
  3. applicationContext.xml
  4. Test.java
In this example, we are using list that can have duplicate elements, you may use set that have only unique elements. But, you need to change list to set in the applicationContext.xml file and List to Set in the Question.java file.
Question.java
This class contains three properties, two constructors and displayInfo() method that prints the information. Here, we are using List to contain the multiple answers.
package com.mycompany;  
  
import java.util.Iterator;  
import java.util.List;  
  
public class Question {  
private int id;  
private String name;  
private List<Answer> answers;  
  
//setters and getters  
  
public void displayInfo(){  
    System.out.println(id+" "+name);  
    System.out.println("answers are:");  
    Iterator<Answer> itr=answers.iterator();  
    while(itr.hasNext()){  
        System.out.println(itr.next());  
    }  
}  
  
}  
Answer.java
This class has three properties id, name and by with constructor and toString() method.
package com.mycompany;  
  
public class Answer {  
private int id;  
private String name;  
private String by;  
  //setters and getters  
public String toString(){  
    return id+" "+name+" "+by;  
}  
 applicationContext.xml
The ref element is used to define the reference of another bean. Here, we are using bean attribute of ref element to specify the reference of another bean.
<?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="answer1" class="com.mycompany.Answer">  
<property name="id" value="1"></property>  
<property name="name" value="Java is a programming language"></property>  
<property name="by" value="Ravi Malik"></property>  
</bean>  
<bean id="answer2" class="com.mycompany.Answer">  
<property name="id" value="2"></property>  
<property name="name" value="Java is a platform"></property>  
<property name="by" value="Sachin"></property>  
</bean>  
  
<bean id="q" class="com.mycompany.Question">  
<property name="id" value="1"></property>  
<property name="name" value="What is Java?"></property>  
<property name="answers">  
<list>  
<ref bean="answer1"/>  
<ref bean="answer2"/>  
</list>  
</property>  
</bean>  
  
</beans>  
Test.java
This class gets the bean from the applicationContext.xml file and calls the displayInfo method.
package com.mycompany;  
  
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 Test {  
public static void main(String[] args) {  
    Resource r=new ClassPathResource("applicationContext.xml");  
    BeanFactory factory=new XmlBeanFactory(r);  
      
    Question q=(Question)factory.getBean("q");  
    q.displayInfo();  
      
}  
}  
Setter Injection with Map Example
In this example, we are using map as the answer for a question that have answer as the key and username as the value. Here, we are using key and value pair both as a string.
Like previous examples, it is the example of forum where one question can have multiple answers.
Question.java
This class contains three properties, getters & setters and displayInfo() method to display the information.
package com.mycompany;  
import java.util.Iterator;  
import java.util.Map;  
import java.util.Set;  
import java.util.Map.Entry;  
  
public class Question {  
private int id;  
private String name;  
private Map<String,String> answers;  
  
//getters and setters  
  
public void displayInfo(){  
    System.out.println("question id:"+id);  
    System.out.println("question name:"+name);  
    System.out.println("Answers....");  
    Set<Entry<String, String>> set=answers.entrySet();  
    Iterator<Entry<String, String>> itr=set.iterator();  
    while(itr.hasNext()){  
        Entry<String,String> entry=itr.next();  
        System.out.println("Answer:"+entry.getKey()+" Posted By:"+entry.getValue());  
    }  
}  
 applicationContext.xml
The entry attribute of map is used to define the key and value information.
<?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="q" class="com.mycompany.Question">  
<property name="id" value="1"></property>  
<property name="name" value="What is Java?"></property>  
<property name="answers">  
<map>  
<entry key="Java is a programming language"  value="Sonoo Jaiswal"></entry>  
<entry key="Java is a Platform" value="Sachin Yadav"></entry>  
</map>  
</property>  
</bean>  
  
</beans>  
Test.java
This class gets the bean from the applicationContext.xml file and calls the displayInfo() method.
package com.mycompany;  
  
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 Test {  
public static void main(String[] args) {  
    Resource r=new ClassPathResource("applicationContext.xml");  
    BeanFactory factory=new XmlBeanFactory(r);  
      
    Question q=(Question)factory.getBean("q");  
    q.displayInfo();  
      
}  
}  
Setter Injection with Non-String Map (having dependent Object) Example
In this example, we are using map as the answer that have Answer and User. Here, we are using key and value pair both as an object. Answer has its own information such as answerId, answer and postedDate, User has its own information such as userId, username, emailId.
Like previous examples, it is the example of forum where one question can have multiple answers.
Question.java
This class contains three properties, getters & setters and displayInfo() method to display the information.
package com.mycompany;  
import java.util.Iterator;  
import java.util.Map;  
import java.util.Set;  
import java.util.Map.Entry;  
  
public class Question {  
private int id;  
private String name;  
private Map<Answer,User> answers;  
  
//getters and setters  
  
  
public void displayInfo(){  
    System.out.println("question id:"+id);  
    System.out.println("question name:"+name);  
    System.out.println("Answers....");  
    Set<Entry<Answer, User>> set=answers.entrySet();  
    Iterator<Entry<Answer, User>> itr=set.iterator();  
    while(itr.hasNext()){  
        Entry<Answer, User> entry=itr.next();  
        Answer ans=entry.getKey();  
        User user=entry.getValue();  
        System.out.println("Answer Information:");  
        System.out.println(ans);  
        System.out.println("Posted By:");  
        System.out.println(user);  
    }  
}  
}  Answer.java
package com.mycompany;  
  
import java.util.Date;  
  
public class Answer {  
private int id;  
private String answer;  
private Date postedDate;  
public Answer() {}  
public Answer(int id, String answer, Date postedDate) {  
    super();  
    this.id = id;  
    this.answer = answer;  
    this.postedDate = postedDate;  
}  
  
public String toString(){  
    return "Id:"+id+" Answer:"+answer+" Posted Date:"+postedDate;  
}  
}  
User.java
package com.mycompany;  
  
public class User {  
private int id;  
private String name,email;  
public User() {}  
public User(int id, String name, String email) {  
    super();  
    this.id = id;  
    this.name = name;  
    this.email = email;  
}  
  
public String toString(){  
    return "Id:"+id+" Name:"+name+" Email Id:"+email;  
}  
}  
applicationContext.xml
The key-ref and value-ref attributes of entry element is used to define the reference of bean in the map.
<?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="answer1" class="com.mycompany.Answer">  
<property name="id" value="1"></property>  
<property name="answer" value="Java is a Programming Language"></property>  
<property name="postedDate" value="12/12/2001"></property>  
</bean>  
<bean id="answer2" class="com.mycompany.Answer">  
<property name="id" value="2"></property>  
<property name="answer" value="Java is a Platform"></property>  
<property name="postedDate" value="12/12/2003"></property>  
</bean>  
  
<bean id="user1" class="com.mycompany.User">  
<property name="id" value="1"></property>  
<property name="name" value="Arun Kumar"></property>  
<property name="email" value="arun@gmail.com"></property>  
</bean>  
<bean id="user2" class="com.mycompany.User">  
<property name="id" value="2"></property>  
<property name="name" value="Varun Kumar"></property>  
<property name="email" value="Varun@gmail.com"></property>  
</bean>  
  
<bean id="q" class="com.mycompany.Question">  
<property name="id" value="1"></property>  
<property name="name" value="What is Java?"></property>  
<property name="answers">  
<map>  
<entry key-ref="answer1" value-ref="user1"></entry>  
<entry key-ref="answer2" value-ref="user2"></entry>  
</map>  
</property>  
</bean>  
  
</beans>  
Test.java
This class gets the bean from the applicationContext.xml file and calls the displayInfo() method to display the information.
package com.mycompany;  
  
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 Test {  
public static void main(String[] args) {  
    Resource r=new ClassPathResource("applicationContext.xml");  
    BeanFactory factory=new XmlBeanFactory(r);  
      
    Question q=(Question)factory.getBean("q");  
    q.displayInfo();  
      
}  
}  
Difference between constructor and setter injection
There are many key differences between constructor injection and setter injection.
  1. Partial dependency: can be injected using setter injection but it is not possible by constructor. Suppose there are 3 properties in a class, having 3 arg constructor and setters methods. In such case, if you want to pass information for only one property, it is possible by setter method only.
  2. Overriding: Setter injection overrides the constructor injection. If we use both constructor and setter injection, IOC container will use the setter injection.
  3. Changes: We can easily change the value by setter injection. It doesn't create a new bean instance always like constructor. So setter injection is flexible than constructor injection.





















4 comments:

  1. Thanks for sharing this informative content , Great work
    Leanpitch provides online training in Agile coach during this lockdown period everyone can use it wisely.
    Certified agile coaching Bangalore

    ReplyDelete
  2. Thanks for sharing this informative content , Great work
    Leanpitch provides online training in Product prototyping during this lockdown period everyone can use it wisely.
    icp-cat training

    ReplyDelete
  3. Thanks for sharing this informative content , Great work
    To crack scrum master interview : Scrum Master Interview Questions

    ReplyDelete
  4. Thanks for sharing this informative content , Great work
    Leanpitch provides online training in ICP CAT during this lockdown period everyone can use it wisely.
    ICP-CAT certification

    ReplyDelete

Java 9 and Java11 and Java17, Java 21 Features

 Java 9 and Java11 and Java17 features along with explanation and examples in realtime scenarios Here's a detailed breakdown of Java 9, ...