Spring Dependency Injection Example

Hello Readers,

This post is an example of achieving Dependency Injection(DI) using our favorite Spring framework 🙂

Dependency Injection is a feature that benefits us by making the classes loosely coupled. The general concept in DI is Inversion of Control (IOC) . A class should not be configuring itself but it should be configured from outside (typically a XML File).

Example:

Consider there are 2 classes viz., Person and Sport. Person HAS-A Sport. But using DI, we will get away from saying

Sport s=new Sport() in the person class. Instead this instance will be created in an XML file and the referece will be given to the Person class.

Following is the example:

1) Person.java

package com.badal.model;

public class Person {

private String firstName;
private String lastName;
private Sport sport;

public Sport getSport() {
return sport;
}
public void setSport(Sport sport) {
this.sport = sport;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}

public void testString(){
System.out.println(this.firstName+": "+this.lastName+": "+this.sport);
}

}

2) Sport.java

package com.badal.model;

public class Sport {

private String favoriteSport;
private String favoriteSportsman;

public String getFavoriteSport() {
return favoriteSport;
}
public void setFavoriteSport(String favoriteSport) {
this.favoriteSport = favoriteSport;
}
public String getFavoriteSportsman() {
return favoriteSportsman;
}
public void setFavoriteSportsman(String favoriteSportsman) {
this.favoriteSportsman = favoriteSportsman;
}

public String toString(){
return this.favoriteSport+": "+this.favoriteSportsman;
}

public static int getScore(){
return 100;
}

}

As mentioned earlier, Person HAS-A Sport.

3) Now we will write the all important XML file. I have named the file as BeanDefs.xml.

There are 2 ways to do DI viz., setter injection and constructor injection. In this example, I have used setter injection.

In Spring, we make a bean instance for each class in the application. We will make a bean instance for each Person.java and Sport.java. We will then inject the sport instance into the person instance.

<pre name="code" class="xml">

<?xml version=”1.0″ encoding=”UTF-8″?>
<beans xmlns=”http://www.springframework.org/schema/beans&#8221;
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xmlns:aop=”http://www.springframework.org/schema/aop&#8221;
xsi:schemaLocation=”http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd”&gt;

<!– Make an instance of Sport.java –>
<bean id=”sportBean” class=”com.badal.model.Sport”>
<property name=”favoriteSport” value=”Cricket” />
<property name=”favoriteSportsman” value=”Sachin Tendulkar”/>
</bean>

<!– Make an instance of Person.java and inject the sport instance using the “ref” attribute. –>

<bean id=”personBean” class=”com.badal.model.Person”>

<property name=”firstName” value=”Badal” />
<property name=”lastName” value=”Chowdhary” />
<property name=”sport” ref=”sportBean” />
</bean>

</beans>

</pre>

4) We have done all the hard work to inject an instance of a class into the property of some other class. Now we have to write a main class (class with main method). In the main method, load the XML file that holds the bean definitions, get the instance of Person that was created in the XML file, and then call any Person or Sport class methods using that instance.

package com.badal.main;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import com.badal.model.Person;

public class SpringSecondMain {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//BeanFactory factory=new XmlBeanFactory(new FileSystemResource("BeanDefs.xml"));
ApplicationContext factory= new FileSystemXmlApplicationContext("BeanDefs.xml");
Person p=(Person) factory.getBean("personBean");
p.testString();
System.out.println(p.getSport().getScore());
}

}

Please make a note that to invoke the getScore() of the Sport class, we did not have to say

Sport s=new Sport(). Instead, we made a bean of Sport (here sportBean) and injected this bean into the sport property of the Person class. This injection was done using the XML file. One more alternative to achieve this would be to use annotations.

You also need to add jar files in your application. I have added the following jars:

1) spring.jar

2) commons-logging.jar

I hope the code works on your machines.

If you like my post, feel free to leave comments 😛

Thank you for taking the time to read!

Best Regards

Advertisements

About Badal Chowdhary

I am a Software Engineer by profession. I have done SCJP and SCWCD certifications. Like working on cutting edge technologies and frameworks. Driven by challenges and fascinated by technology. I love playing and watching sports: Cricket, Ping Pong, Tennis, Badminton, Racket Ball and Gym.
This entry was posted in Spring and tagged , . Bookmark the permalink.

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