Thursday, April 26, 2012

Spring Framework- Initialize values of bean (property tag)


First to develop applications with the Spring framework need to setup the environment . Development requirements  are-
1. Eclipse.
2.JDK 1.6.0
3.Spring framework 3.0(Click here to download).
Add the spring jar files into CLASSPATH or Eclipse Library.

Now discuss about example-
 Create a class Point.java
 

package com.spring.test;

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;
}
}
Create a XML file spring.xml

<?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 class="com.spring.test.Point" id="point">
<property name="x" value="0"></property>
<property name="y" value="10"></property>
</bean>
</beans>




Create a Main class to access the beans using XML DrawApp.java
package com.spring.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class DrawApp {
public static void main(String[] args)
{
ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
Point p= (Point)context.getBean("point");
System.out.print("x is="+p.getX);
System.out.print("y is="+p.gety);
}
}

Now execute the project. it show the values of X and Y.

--> In place of ApplicationContext here can also use BeanFactory.


For Further Reading,
General, Java, spring, Technology

0 comments:

Post a Comment


 

Site Status

Man Behind Technical Today

Hello, I am Navin Bansal. I am a student of MCA in Rajsthan Institute of Engineering and Technology and owner of this blog. I share my view and ideas among people.