Constructor Injection in Spring Example
Constructor Injection is a wiring technique where dependencies are passed as arguments of the constructors with representing property
employee.java
package com.javainfinite; public class employee { private String ename; private int id; public employee(String ename) { this.ename=ename; } public employee(int id) { this.id=id; } public employee(String ename, int id) { this.ename=ename; this.id=id; } public String getEname() { return ename; } public int getId() { return id; } public void display() { System.out.println("From String ename constructor: "+getEname()); System.out.println("From int id constructor: "+getId()); System.out.println("From String ename and int ID constructor: "+getEname()+" "+getId()); } }
Note: There are no setter methods in employee.java
operational.java
package com.javainfinite; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class operational { public static void main(String args[]) { ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml"); employee emp=(employee) ac.getBean("employee"); emp.display(); } }
applicationContext.xml
<?xml version='1.0' encoding='UTF-8' ?> <!-- was: <?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" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> <bean id="employee" class="com.javainfinite.employee"> <constructor-arg value="Alpha"/> <constructor-arg value="23" type="int"/> </bean> </beans>