Constructor Injection is a type of Dependency Injection in IoC design pattern.
This Java example shows how to use Constructor Injection in Spring Framework.
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"> <property name="name" value="Prasanna"/> <property name="age" value="26"/> <!--Setter Injection --> <property name="address" ref="addressBean"/> </bean> <bean id="addressBean" class="com.javac.Address"> <property name="city" value="Amravati"/> <property name="state" 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 21 22 23 24 25 26 27 28 29 |
package com.javac; public class Employee { private String name; private int age; private Address address; @Override public String toString() { return "Name: "+name+"\n"+"Age: "+age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } } |
Address.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package com.javac; public class Address { private String city; private String state; @Override public String toString() { return "City: "+city+"\n"+"State: "+state; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; } } |
EmployeeAddress.java
1 2 3 4 5 6 7 8 9 10 11 12 13 |
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