Thursday 13 May 2010

Example program for Injecting Objects

Example program: steps: (Error in this program)
1. import the jar files (set the class path)
2. xml file
3. java files






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

import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
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"));
ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
Triangle triangle=(Triangle)context.getBean("triangle");
triangle.draw();
}

}

/*Point.java*/

package org.rajendra.spring;

public class Point
{
private int x;
private int y;
public int getX()
{
return x;
}
public void setX(int x)
{
this.x = x;
}
public int getY()
{
return y;
}
public void setY(int y)
{
this.y = y;
}


}
//Triangle.java

package org.rajendra.spring;

public class Triangle 
{
private Point pointA;
private Point pointB;
private Point pointC;
//use spring dependency injection to pre populate
 public Point getPointA() {
return pointA;
}

public void setPointA(Point pointA) {
this.pointA = pointA;
}

public Point getPointB() {
return pointB;
}

public void setPointB(Point pointB) {
this.pointB = pointB;
}

public Point getPointC() {
return pointC;
}

public void setPointC(Point pointC) {
this.pointC = pointC;
}

public void draw()
 {
System.out.println("Point A=("+getPointA().getX()+","+getPointA().getY()+")");
System.out.println("Point B=("+getPointB().getX()+","+getPointB().getY()+")" );
System.out.println("Point c=("+getPointC().getX()+","+getPointC().getY()+")");
 
 }
}

//spring.xml file

<?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">
 <property name="pointA" ref="zeroPoint"/>
 <property name="pointB" ref="point2"/>
 <property name="pointC" ref="point3"/>
 </bean>
         

<bean id="zeroPoint" class="org.rajendra.Point">
 <property name="x" value="0"/>
 <property name="y" value="0"/>
</bean>
<bean id="point2" class="org.rajendra.Point">
 <property name="x" value="-20"/>
 <property name="y" value="0"/>
</bean>
<bean id="point3" class="org.rajendra.Point">
 <property name="x" value="20"/>
 <property name="y" value="0"/>
</bean>
</beans>




No comments:

Post a Comment