Reputation: 11
I have following classes defined in spring project
public class Triangle
{
private double breadth;
private double length;
public double getBreadth() {
return breadth;
}
public void setBreadth(double breadth) {
this.breadth = breadth;
}
public double getLength() {
return length;
}
public void setLength(double length) {
this.length = length;
}
}
Below class calculates the area of triangle
public class Area
{
Triangle triangle;
public Triangle getTriangle() {
return triangle;
}
public void setTriangle(Triangle triangle) {
this.triangle = triangle;
}
public double triArea()
{
return (triangle.getBreadth() * triangle.getLength())/2;
}
}
spring.xml configuration file is shown below
<?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="src.jayant.spring.Triangle" scope="prototype">
<property name = "breadth" value = "20"/>
<property name = "length" value = "20"/>
</bean>
<bean id="area" class="src.jayant.spring.Area">
<property name = "triangle" ref="triangle"/>
</bean>
</beans>
Finally we have AreaApp.java which gets both 'area' and 'triangle' beans defined in the xml and calculates the area.
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AreaApp
{
public static void main(String args [])
{
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
Triangle triangle = (Triangle)context.getBean("triangle");
Area area = (Area)context.getBean("area");
System.out.println("Area of Triangle is : "+area.triArea());
triangle.setBreadth(40);
System.out.println("Area of Triangle is : "+area.triArea());
}
}
Now
When we have 'triangle' bean scope as 'singleton'
<bean id="triangle" class="src.jayant.spring.Triangle" scope="singleton">
then output will be
Area of Triangle is : 200.0
Area of Triangle is : 400.0
but when I change scope to 'prototype'
<bean id="triangle" class="src.jayant.spring.Triangle" scope="prototype">
then output will be
Area of Triangle is : 200.0
Area of Triangle is : 200.0
Why the setter method
triangle.setBreadth(40);
have no effect when bean scope is prototype.
Thanks
Jay
Upvotes: 0
Views: 230
Reputation: 691685
It does have an effect: it changes the breadth of the triangle you got from the context.
But this triangle is not the same triangle as the one used by the Area
bean, since your triangle bean is now a prototype, and thus, by definition of the prototype scope, you get a new instance every time you ask a Triangle instance to the context.
Upvotes: 3