Spring Basic Dependency Injection Example

Here I give examples on Spring Dependency Injection

Basic Dependency Injection – Spring container will create object for a class during run-time to invoke a business method of that class.

Basic Dependency Injection

Here we create a class called “Triangle”, which have draw() method. So here I shwo how spring will create instance for Triangle class and how we are going to invoke the draw() method,


package com.saravanansivaji.spring;
import com.saravanansivaji.annotations.Description;

@Description("Basic Spring DI demo")
public class Triangle {

@Description("Spring container will create object instance for this class"
+ " during runtime, which will help us to invoke the below draw() method" )
public void draw() {
System.out.println("Triangle drawn!!");


Next I define my spring.xml configuration file,

<!DOCTYPE beans PUBLIC “-//SPRING//DTD BEAN 2.0//EN” “http://www.springframework.org/dtd/spring-beans-2.0.dtd&#8221; >
<!– Basic Dependency Injection Demo –>
<bean id=”triangle” class=”com.saravanansivaji.spring.Triangle” />

Next, the application class “SpringDI.java” which make use of the Triangle class,

public class SpringDI {

public static void main(String[] args) {
//BeanFactory factory = new XmlBeanFactory(new )

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

Triangle triangle = (Triangle) context.getBean("triangle"); //NOTE: we didn't use new operator here to create object


Triangle drawn!!



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: