Sunday 5 February 2017

Spring: Injecting properties

In my previous post, I explained constructor based dependency injection. Spring provides another way also, where you can inject properties of bean using setter methods.
public class Employee {
 private int id;
 private String firstName;
 private String lastName;
}

We can inject properties to Employee class like below.
 <bean id="1" name="Krishna" class="com.sample.pojo.Employee">
  <property name="id" value="543216" />
  <property name="lastName" value="Gurram" />
  <property name="firstName" value="Hari Krishna" />
 </bean>


Following is the complete working application.


Employee.java
package com.sample.pojo;

public class Employee {
 private int id;
 private String firstName;
 private String lastName;

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Employee [id=").append(id).append(", firstName=").append(firstName).append(", lastName=")
    .append(lastName).append("]");
  return builder.toString();
 }

}

myConfiguration.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"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

 <bean id="1" name="Krishna" class="com.sample.pojo.Employee">
  <property name="id" value="543216" />
  <property name="lastName" value="Gurram" />
  <property name="firstName" value="Hari Krishna" />
 </bean>

</beans>

HelloWorld.java
package com.sample.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.sample.pojo.Employee;

public class HelloWorld {
 public static void main(String args[]) {
  ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "myConfiguration.xml" });

  Employee employee = context.getBean("Krishna", Employee.class);

  System.out.println(employee);

  ((ClassPathXmlApplicationContext) context).close();
 }
}

Output
Employee [id=543216, firstName=Hari Krishna, lastName=Gurram]




Previous                                                 Next                                                 Home

No comments:

Post a Comment