0

Below is my Pojo:

public class Triangle implements ApplicationContextAware, BeanNameAware{

   private Point pointA;
   private Point pointB;
   private Point pointC;

My springs.xml's structure goes here:

<bean id="pointA" class="com.betta.springtest.Point">
        <property name="x" value="0" />
        <property name="y" value="0" />
    </bean>

    <bean id="pointB" class="com.betta.springtest.Point">
        <property name="x" value="-20" />
        <property name="y" value="0" />
    </bean>

    <bean id="pointC" class="com.betta.springtest.Point">
        <property name="x" value="20" />
        <property name="y" value="0" />
    </bean>

    <bean id="triangle-bean" class="com.betta.springtest.Triangle" autowire="autodetect"/>

    <alias name="triangle-bean" alias="triangle" />

I have implemented ApplciationContextAware and setting context in the POJO. After the getting the bean from the context, I changed the value of one of the properties(bean) of the bean. Again I got the fresh child bean from the context, but I am not getting it with the values set in spring.xml. Here goes my code, can anyone tell me whats wrong here or is it the expected behavior?

public void draw(){

    System.out.println("Point A "+this.pointA.getX()+" "+this.pointA.getY());
    System.out.println("Point B "+this.pointB.getX()+" "+this.pointB.getY());
    System.out.println("Point C "+this.pointC.getX()+" "+this.pointC.getY());
    System.out.println("Changing the value of point B");
    this.pointB.setX(0);
    this.pointB.setY(0);
    System.out.println(" After Changing the value of point B "+
            this.pointB.getX()+" "+this.pointB.getY());
    Point newPoint = (Point) this.context.getBean("pointB");
    System.out.println("Restored value of point B "+
            newPoint.getX()+" "+newPoint.getY());

}

In the above code, I want the object Point B with the values set in springs.xml, which I am not able to obtain. I am new to Spring, can anyone help me in understanding this concept?

Betta
  • 416
  • 5
  • 17

1 Answers1

1

Spring beans are singleton by default. That means that you will only have one instance of your bean per application context instance. And if you modify the instance retrieved from application context, it will still be modified when you retrieve it again, because only single instance of it exists.

You could use prototype bean scope, which means that new bean instance will be created each time you retrieve it from application context, in which case the code would behave as you expect.

<bean id="pointA" class="com.betta.springtest.Point" scope="prototype">
    <property name="x" value="0" />
    <property name="y" value="0" />
</bean>
Bohuslav Burghardt
  • 33,626
  • 7
  • 114
  • 109