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,

Triangle.java

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; >
<beans>
<!– Basic Dependency Injection Demo –>
<bean id=”triangle” class=”com.saravanansivaji.spring.Triangle” />
</beans>

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.draw();
}
}

Output

Triangle drawn!!

Thanks!!

Advertisements

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: