Wednesday, June 13, 2012

Spring Framework- inner bean example


Spring framework  contain different types of bean properties injctions provided.one of them is inner bean injection.this is look like java inner classes,classes that are defined with in the scope of other class is known as inner class. similarly inner beans are beans that are defined with in the scope of another bean. To illustrate this let see a example-
Directory structure of project -



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 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 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();
}
}
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="circle" class="com.test.Circle">
<property name="p" >
<bean class="com.test.Point">
<property name="x" value="10"></property>
<property name="y" value="30"></property>
</bean>
</property>
</bean>
</beans>

Here com.test.Point is inner bean which have no reference and id. this bean is define in scope of another bean so this work as  private bean.

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


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.