Injecting dependencies with spring

Any typical software application consists of a collection of objects that interact with each other to meet a business goal. Each object depends on other objects; hence they need references of those objects to interact with them. The traditional approach was to create these references by themselves, which resulted in tight coupling between the application objects.

In Spring, objects don’t need to create their dependencies, they are given the dependencies by the Spring container. This mechanism of injecting dependencies into an object, rather than the object asking for it is called as dependency injection.

Java Classes

We had created some simple java classes to demonstrate Spring Dependency Injection (DI). The java classes are shown below.

package examples;

public interface Vehicle {
    public void start();
    public void control();
    public void stop();
}
package examples;

public class Bus implements Vehicle{

    public void start() {
	System.out.println("Starting Bus");
    }
	
    public void control(){
	System.out.println("Driving  Bus");
    }
	
    public void stop() {
 	System.out.println("Stoping Bus");
    }
}
package examples;

public class Driver {
	
    private Vehicle vehicle;
	
    public void drive(){
	vehicle.start();
	vehicle.control();
	vehicle.stop();
    }

    public Vehicle getVehicle() {
	return vehicle;
    }

    public void setVehicle(Vehicle vehicle) {
	this.vehicle = vehicle;
    }
}

Notice that the above Driver class requires an object of Vehicle class to drive the vehicle. In the tradition approach we would have created this dependency in the Driver class itself by using a new operator as shown below:

public void drive(){
    vehicle = new Bus();
    vehicle.start();
    vehicle.control();
    vehicle.stop();
}

Even though the above approach works, it would create a very tight coupling between the Driver and the Bus. What if we want the driver to drive a car?

We can overcome the above drawback by using Spring DI.

Configuring Spring Beans

All spring related beans are configured and managed in the Spring container. This container is known as Bean Factory or Application Context. We can declare these beans in an xml file. Let’s call it as applicationContext.xml.

<?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.org/schema/context"
	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-4.0.xsd">
	
	<bean name="bus" class="examples.Bus" />
	
	<bean name="driver" class="examples.Driver">
	     <property name="vehicle" ref="bus"></property>
	</bean>		
</beans>

In the above xml file we have configured our Bus and Driver objects as Spring beans. Notice that the Bus object is injected into the Driver object by using property. This kind of injection is called as setter injection. It uses the setter method in the Driver class to inject the vehicle property into it.

We could also use another kind of injection called as constructor injection, where the dependency is injected into the object by using the constructor. We can inject the bus object to the driver object by using constructor injection as shown below:

<bean name="driver" class="examples.Driver">
    <constructor-arg ref="bus"/>
</bean>	

We need to have a parameterized constructor in the Driver class that accepts bus as a parameter as shown below::

public Driver(Vehicle vehicle){
    this.vehicle = vehicle;
}

Testing the Code

To test the code we will create the spring application context and configure our beans using the applicationContext.xml file. Shown below is the sample code:

package examples;

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

public class DriverMain {

    public static void main(String[] args) {
	ApplicationContext cntx = new ClassPathXmlApplicationContext("applicationContext.xml");
	Driver driver = (Driver)cntx.getBean("driver");
	driver.drive();
    }
}

POPULAR ARTICLES

Creating Conditional Beans in Spring

The concept of condition beans enables Spring to restrict the creation of any bean depending on the evaluation of a condition. These beans get created only when a preset condition is evaluated as true

View Article

Accepting Request Param and Path Variable in Spring Controller

Spring MVC provides various ways through which a client browser can pass data to the Controller. In this article we will discuss about accepting Request Parameters and Path Variables in Spring Contr..

View Article

Generate Namespace & Schema Information using JAXB

Most xml documents used in enterprise applications makes use of namespace to avoid element name conflicts. This article talks about generating these namespace and schema information when marshaling...

View Article

Switching Database Profile using Spring Profiles

We are most likely to have separate db configuration for different environment like development and production environment. Spring profiles provide a convenient way to switch db profiles at runtime.

View Article

SQL and its Sub-Languages

SQL (Structured Query Language) is a language understood by most modern databases. It is an ANSI (American National Standard Institute) standard language which is used to manipulate databases.

View Article

Introducing JUnit Rule

Junit Rules allows developers to add additional functionalities that can applied to all test methods in a test class. It is similar to the concept of custom test runners but with reduced restrictions.

View Article

Addressing Ambiguity in Spring Autowiring

Spring autowiring is powerful concept, but we should be very cautious while using it. We may end up in creating ambiguity while autowiring beans, which will cause autowiring to fail.

View Article

Creating and Using Synonym in Oracle Database

Synonyms are database objects used to provide duplicate names to existing objects in the database. It is just an alternate name used to hide the original name of the object.

View Article

Creating and Using Sequence in Oracle Database

A sequence is used to auto-generate numbers in ascending or descending order which can serve as a primary key or a part of it (in case of composite key).

View Article

Creating and Manipulating Constraints in Oracle Database

Constraints are used to impose certain rules on columns to avoid invalid data entry into the table. If any of the constraint is violated the operation fails.

View Article

Integrating Log4J with Perf4J for Performance Logging

Perf4j is an open source logging framework used primarily for monitoring performance statistics in java applications. Log4j has the ability to integrate with perf4j to capture performance data.

View Article

Tagging in GIT

Tagging allows us to mark a specific point in the commit history or snapshot. A tag is typically used to mark a project release. This article shows how to create tags in Git.

View Article