Thursday, November 22, 2018
Home > Spring > Spring setter injection example in eclipse

Spring setter injection example in eclipse

Spring setter injection example

We can do inject values by setter injection method also. The <property> tag 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.

In this tutorial, we will learn how to set the property of a class by spring setter injection with an example.


Ecplise IDE : Ecplise Luna

Spring setter injection example in eclipse

Jars: Placed below jar in “Referenced Libraries” Folder

  1. commons-logging-1.2
  2. spring-beans-5.0.8.RELEASE
  3. spring-context-5.0.8.RELEASE
  4. spring-core-5.0.8.RELEASE

To create this example, we have created 3 files inside src directory

  1. Employee.java
  2. spring.xml
  3. client.java

In below Employee class, We have three property gender, age, and email. We are going to inject this property by using setter injection.

Employee.java

package beans;

public class Employee{
  private String gender;
  private int age;
  private String email;
  String name;

  public void setGender(String gender) {
    this.gender = gender;
  }
    
  public void setAge(int age) {
    this.age = age;
  }
  public void setEmail(String email) {
    this.email = email;
  }
  public void hello(String name)
  {
    System.out.println("Good Mornig "+gender+" "+name);
    System.out.println("your age: "+age);
    System.out.println("Your Email id: "+email);
  }
}

In Spring.xml file we are going to insert property detail as mentioned below.

Spring.xml

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
      "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
  <bean id="g" class="beans.Employee">
    <property name="gender" value="Mr"/>
    <property name="age"><value>18</value></property>
    <property name="email" value="[email protected]"/>
  </bean>
</beans>

In below Client.java, We will use ApplicationContext IoC container then we will use configuration file spring.xml.

package Client;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import beans.Employee;
public class Test 
{
  public static void main(String[] args) 
  {
    ApplicationContext ap= new ClassPathXmlApplicationContext("resources/spring.xml");
    Employee g=(Employee)ap.getBean("g");
    g.hello("john");
  }
}

OUTPUT:

Good Mornig Mr John
your age: 18
Your Email id: [email protected]

Related Topics:-


You may also like :-

Admin
We are group of application developer and admin.We are providing good content of information about IT technology and services .

Leave a Reply

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