This Java example shows how to use Constructor Injection in Spring Framework.
Constructor Injection is a type of Dependency Injection in IoC design pattern.
spring-config.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?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-3.0.xsd"> <bean id="employeeBean" class="com.javac.Employee"> <constructor-arg type="java.lang.String" value="Prasanna"/> <constructor-arg type="int" value="26"/> <!--Constructor Injection --> <constructor-arg type="Address" ref="addressBean"/> </bean> <bean id="addressBean" class="com.javac.Address"> <constructor-arg index="0" value="Amravati"/> <constructor-arg index="1" value="Maharashtra"/> </bean> </beans> |
Employee.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package com.javac; public class Employee { private String name; private int age; private Address address; public Employee(String name, int age, Address address) { this.name = name; this.age = age; this.address = address; } public Address getAddress() { return address; } @Override public String toString() { return "Name: "+name+"\n"+"Age: "+age; } } |
Address.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package com.javac; public class Address { private String city; private String state; public Address(String city,String state) { this.city = city; this.state = state; } @Override public String toString() { return "City: "+city+"\n"+"State: "+state; } } |
EmployeeAddress.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package com.javac; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; public class EmployeeAddress { public static void main(String[] args) { ClassPathResource resource = new ClassPathResource("spring-config.xml"); BeanFactory factory = new XmlBeanFactory(resource); Employee employee = (Employee)factory.getBean("employeeBean"); System.out.println("Employee: "+employee); System.out.println("Address: "+employee.getAddress()); } } |
Output:
INFO: Loading XML bean definitions from file [D:\workspace\SpringProject\src\spring-config.xml]
Employee: Name: Prasanna
Age: 26
Address: City: Amravati
State: Maharashtra
Employee: Name: Prasanna
Age: 26
Address: City: Amravati
State: Maharashtra