Friday, 7 May 2010

Example program for springs

Example program for dependency injection: with using springs and without using spring

/*  DrawingApp.java */
package org.rajendra.spring;

public class DrawingApp 
{
public static void main(String args[])
{
Triangle triangle=new Triangle();

triangle.draw();
}

}
javac DrawingApp.java

package org.rajendra.spring;

public class Triangle 
{
 public void draw()
 {
System.out.println("Triangle drawn");
 
 }
}

javac Triangle .java
java DrawingApp

//with using spring:
  • download the spring jar files
  • set the class path of spring jar files
like below


package org.rajendra.spring;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;

public class DrawingApp 
{
public static void main(String args[])
{
//Triangle triangle=new Triangle();
//using bean Factory
BeanFactory factory=new XmlBeanFactory(new FileSystemResource("spring.xml"));
Triangle triangle=(Triangle)factory.getBean("triangle");
triangle.draw();
}

}




package org.rajendra.spring;

public class Triangle
{
 public void draw()
 {
System.out.println("Triangle drawn");

 }
}


  • now create a xml file for beans

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
 <bean id="triangle" class="org.rajendra.spring.Triangle"/>
</beans>

  • now execute the program

No comments:

Post a Comment