Spring Constructor Injection

In Spring framework, a dependency can be injected in a couple of ways.

  1. Constructor Injection
  2. Setter Injection

In this example we will visit Spring’s Constructor Injection feature. Here is how my example project’s layout looks like.

It’s a maven project, so pom.xml contains basic dependencies.


<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.bharat.spring.ioc</groupId>
	<artifactId>spring-ioc-tutorial</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<properties>
		<spring.version>3.1.2.RELEASE</spring.version>
	</properties>

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

We have a Class Employee


package com.bharat.spring.ioc;

public class Employee {

	private int id;
	private String name;
	private int age;
	
	private Vehicle car;
	
	public Employee() {
	}

	public Employee(int id, String name, int age, Vehicle car){
		this.id = id;
		this.name = name;
		this.age = age;
		this.car = car;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	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 Vehicle getCar() {
		return car;
	}
	
	public void setCar(Vehicle car) {
		this.car = car;
	}
	
}

Employee has a few dependencies id, name, age and “Vehicle” (Assuming each employee has a Vehicle) defined by Vehicle Interface. Vehicle Interface has a method drive() which defines Vehicle’s behaviour of getting driven.

package com.bharat.spring.ioc;

public interface Vehicle {

	public void drive();
	
}

Vehicle Interface is implemented by a Car class as below.

package com.bharat.spring.ioc;

public class Car implements Vehicle {

	
	public void drive() {
		System.out.println("Employee Driving  a CAR.");
	}

}

Now these classes and Interfaces are woven in spring using an xml file or java metadata (annotations). We prefer traditional xml configuration for our exmples. So here is how our xml configuration file looks like.


<?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.xsd">

	<bean id="bharat" class="com.bharat.spring.ioc.Employee">
		<constructor-arg name="id" value="1001"/>
		<constructor-arg name="name" value="Bharat Sharma"/>
		<constructor-arg name="age" value="30"/>
		<constructor-arg name="car" ref="car"/>
	</bean>
	
	<bean id="car" class="com.bharat.spring.ioc.Car"/>
	
</beans>

ah.. so we have enough plumbing code now, lets do some real work!

Things roll in action in our MainClass as below


package com.bharat.spring.ioc;

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

public class MainClass {

	public static void main(String[] args) {

		ApplicationContext context = new ClassPathXmlApplicationContext(
				"spring-config.xml");

		Employee bharat = (Employee) context.getBean("bharat");

		System.out.println("id : " + bharat.getId() + ", Name : "
				+ bharat.getName() + " Age : " + bharat.getAge());
		bharat.getCar().drive();
	}
}

On running above example code we see following output.


id : 1001, Name : Bharat Sharma Age : 30
Employee Driving  a CAR.

In Spring IOC container “id” is unique and a way to reference the instance of our class. In a Spring driven application we let container create instances of all the required classes and inject there depencies as mentioned in a xml configuration file. spring-config.xml in our case. Spring’s IOC container reads this xml file and creates all the instances defined in there and injects dependencies as per our requirement mentioned in Spring config.

In our spring-config.xml file we declare an instance of our Employee bean with an id “bharat” and an instance of class Car with id “car”. Now class Employee has a parametarized constructor which we will use to create instance with appropriate values. Class employee has dependencies(id, name, age) which are injected in the class using

<construtor-arg name="..." value="..." />

This is a way of injecting basic datatypes in spring. To inject complex datatype we use

<construtor-arg name="..." ref="..." />

where “ref” is the id of other complex class. In our java code we ask spring IOC container for instances of our classes instead of creating one on our own. This is typically done as below.

ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");

Employee bharat = (Employee) context.getBean("bharat");
Advertisements

, , , , , , ,

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: