This article will explore a specific type of DI technique called Constructor-Based Dependency Injection within Spring. We can inject the dependency by constructor.The constructor-arg subelement of bean is used for constructor injection.
Let’s see the simple example to learn how to set a bean property via constructor injection. We have created three files here:
- Students.java
- applicationContext.xml
- Test.java
Students.java
The Students bean class has two attributes like id, and name. All the two attributes are set thru constructor injection. The
0 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 |
package com.codeNuclear; public class Students { private int id; private String name; public Students(int id) { this.id = id; } public Students(String name) { this.name = name; } public Students(int id, String name) { this.id = id; this.name = name; } void show() { System.out.println("ID:" +id +" "+"Name:"+name); } } |
applicationContext.xml
We are providing the information into the bean by this file. The
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?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-2.5.xsd"> <bean id="StudentDetail" class="com.codeNuclear.Students"> <constructor-arg value="10" type="int"> </constructor-arg> </bean> </beans> |
Test.java
This class gets the bean from the applicationContext.xml file and calls the show method.
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package com.codeNuclear; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; public class Test { public static void main(String[] args) { Resource r=new ClassPathResource("applicationContext.xml"); BeanFactory factory=new XmlBeanFactory(r); Students s = (Students)factory.getBean("StudentDetail"); s.show(); } } |
Output
Injecting string-based values
If you don’t specify the type attribute in the constructor-arg element, by default string type constructor will be invoked and the output will be 0 20.
0 1 2 3 4 5 6 7 |
<bean id="StudentDetail" class="com.codeNuclear.Students"> <constructor-arg value="20"> </constructor-arg> </bean> |
Output
You may also pass the string literal as following:
0 1 2 3 4 5 6 7 |
<bean id="StudentDetail" class="com.codeNuclear.Students"> <constructor-arg value="Smith"> </constructor-arg> </bean> |
Output
You may pass integer literal and string both as following:
0 1 2 3 4 5 6 7 8 9 10 |
<bean id="StudentDetail" class="com.codeNuclear.Students"> <constructor-arg value="20" type="int"> </constructor-arg> <constructor-arg value="Smith"> </constructor-arg> </bean> |
Output