Spring Constructor Injection

In this example , we will see Second type of dependency injection in Spring i.e. Contructor Injection –

Tools used to create below project – 

  1. Spring 5.0.7.RELEASE
  2. Maven 3.3
  3. Java 8
  4. Eclipse Neon.2

Github Link :   Download

Step 1: Create Simple Maven Project with Spring Configuration

Step 2: Configure maven dependencies

Below pom.xml file contains the dependencies required for spring project –

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.myjavablog</groupId>
<artifactId>SpringConstructorInjection</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>SpringConstructorInjection</name>
<url>http://maven.apache.org</url>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>5.0.7.RELEASE</spring.version>
</properties>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>

<!-- Spring 5 dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>

</dependencies>
</project>

Below project structure will be created for you by Eclipse .


 

 

 

 

 

 

Step 3:  Create Employee.java and Address.java under com.myjavablog.beans package –

Employee.java

package com.myjavablog.beans;

/**
* @author anupb
*
*/
public class Employee {

private String name;
private Address address;

public Employee(String name, Address address) {
super();
this.name = name;
this.address = address;
}

public String getName() {
return name;
}

public Address getAddress() {
return address;
}

@Override
public String toString() {
return "Employee [name=" + name + ", address=" + address + "]";
}

}

Address.java

package com.myjavablog.beans;

/**
* @author anupb
*
*/
public class Address {

private String city;
private String 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;
}

@Override
public String toString() {
return "Address [city=" + city + ", state=" + state + "]";
}

}

These are bean files where we have only getters and setters defined.

Step 4: Create ApplicationContext.xml under /src/main/resources-

ApplicationContext.xml

<div id="crayon-5b537011533c5704156605-2" class="crayon-line crayon-striped-line">

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

<bean id="EmployeeBean" class="com.myjavablog.beans.Employee">
<constructor-arg index="0" type="java.lang.String" value="Anup" />
<constructor-arg index="1" ref="AddressBean" />
</bean>
<bean id="AddressBean" class="com.myjavablog.beans.Address">
<property name="city" value="Pune"></property>
<property name="state" value="Maharashtra"></property>
</bean>

</beans>

</div>

You must have noted here that, Employee class has dependency on Address class. So Address is injected into the Employee through Dependency Injection . And as we have initialized address object through constructor in Employee class this is called Constructor Dependency Injection. Here ref=”AddressBean” is a reference to AddressBean and its injected into Employee object through Employee Constructor.

Here We have declared two beans with corresponding ids.
1.Class Employee with id as “EmployeeBean”
2.Class Address with id as “AddressBean”
constructor-arg tag is used for providing argument to bean’ s

constructor.type is for declaring data types and index defines position in constructor’s argument.

In above xml,Two arguments are passed.
1. Anup as string
2. AddressBean‘s reference to Address Object

Step 5: Create a ConstructorMethodMain.java under com.myjavablog package –

package com.myjavablog;

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

import com.myjavablog.beans.Address;
import com.myjavablog.beans.Employee;

public class ConstructorMethodMain {
public static void main(String[] args) {
@SuppressWarnings("resource")
ApplicationContext beanFactory = new ClassPathXmlApplicationContext("ApplicationContext.xml");

Employee beanInstance = (Employee) beanFactory.getBean("EmployeeBean");

Address add = beanInstance.getAddress();
System.out.println("Employee Name:" + beanInstance.getName() +" City: "+ add.getCity() +" State: "+add.getState());
}
}

We have created ApplicationContext which actually loads bean definitions from XML configuration.

Step 6: Clean and install project

Now run the maven clean install phase as below –

Command:  mvn clean install

OR

Right click on project -> Debug As -> Maven build . Below popup will come up –


 

 

 

 

 

 

 

Step 7: Run the spring application as Java Application

 

 

 

 

 

 

 

 

Output:

Employee Name:Anup City: Pune State: Maharashtra

Leave a Comment

Bitnami