Thursday, May 24, 2012

Spring Framework-An example of Constructor argument.


In this example describe that how to call the constructor of a class in xml file.In xml file basically use <constructor-arg/> tag as a sub tag in <bean/> tag. The detail example as follows-
Directory structure of project-
Class Triangle.java

package com.test;

public class Triangle {

private String type;
private int height;
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public Triangle(String type,int height)
{
this.type=type;
this.height=height;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public void draw()
{
System.out.println( getType()+"Triangle.\n The height is="+getHeight() );
}
}
Class DrawApp.java
package com.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class DrawApp {
public static void main(String a[])
{
ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
Triangle tri= (Triangle) context.getBean("triangle");
tri.draw();
}
}
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 id="triangle" class="com.test.Triangle">
<constructor-arg value="equilateral"/>
<constructor-arg value="10"/>
</bean>
</beans>


The Output is-
equilateralTriangle.
 The height is=10


For Further Reading,
General, Java, spring

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.