Friday, June 15, 2012

How to import xml file in another xml ?


We can split our container definition in many xml file and can use it  in diffrent manner.One of them,load all xml in ApplicationContext or BeanFactory. Another is import all xml file in a perticular xml file now load this single xml in context.
Here we discuss that how to import a xml file into another xml file.for this use <import > tag in <beans> tag and set the path of xml in resource  property of import tag. To illustrate it lets see a example-
Directory Structure-

Class Circle.java
package com.test;

public class Circle {
private Point p;
public Point getP() {
return p;
}
public void setP(Point p) {
this.p = p;
}
public void show()
{
System.out.println("Points are:\n X="+p.getX()+"\n Y="+p.getY());
}
}
Class Point.java
package com.test;

public class Point {
private int x,y;
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public Point(int x, int y) {
super();
this.x = x;
this.y = y;
}
public Point() {
super();
}
}
Class Main.java
package com.test;

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

public class Main {

public static void main(String args[]) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("spring.xml");
ctx.getBean("circle", Circle.class).show();
}
}

Xml file Other.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 name="point" class="com.test.Point">
<property name="x" value="10"></property>
<property name="y" value="20"></property>
</bean>
</beans>


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>
<import resource="Other.xml"/>
<bean id="circle" class="com.test.Circle">
<property name="p" ref="point"></property>
</bean>
</beans>



Output is-
Points are:
X=10
Y=20


For Further Reading,
General, How To, 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.