1

This is my spring configuration file :

   <bean id="controller" class="com.sample.controller.Controller">
       <property name="message" value="Controller1"/>
   </bean>
   <bean id="controller2" class="com.sample.controller.Controller2">
       <property name="message" value="#{controller.message}"/>
   </bean>

And the code :

 ApplicationContext context = 
         new ClassPathXmlApplicationContext("beans.xml");

  Controller obj = (Controller) context.getBean("controller");

  System.out.println(obj.getMessage());
  obj.message = "Controller1 changed!";

  Controller2 obj2 = (Controller2) context.getBean("controller2");
  System.out.println(obj2.getMessage());

I wanted the output to be :

Controller1
Controller1 changed!

but it is

Controller1
Controller1

Is there a simpler way to get the updated value other than injecting Controller into Controller1?

Thank you.

sharma sharma
  • 87
  • 3
  • 8

1 Answers1

0

define property message as bean it self

<bean id="message" class="java.lang.String">
    <constructor-arg value="Controller1"/>
</bean>

and change the original bean configuration

   <bean id="controller" class="com.sample.controller.Controller">
       <property name="message" ref="message"/>
   </bean>
   <bean id="controller2" class="com.sample.controller.Controller2">
       <property name="message" ref="message"/>
   </bean>

Now change the message in java code by

  String obj = (String) context.getBean("message");

and add it back to context

Community
  • 1
  • 1
jmj
  • 237,923
  • 42
  • 401
  • 438
  • Can you elaborate? Did you mean another bean (defined in config also) that just has 'message' as a member variable? – sharma sharma Aug 01 '13 at 21:51
  • That should work. Thanks for the solution! Is there no other way for this? This way, I have to list out all the member variables I want to pass from one class to another (like lists, maps). – sharma sharma Aug 01 '13 at 21:54
  • yeah you could have a Map as bean as well – jmj Aug 01 '13 at 22:03
  • How do you specify the type of the List? Like a list of Strings or List of Foo? I don't have any elements to add in 'ref' initially so there should be some way to tell Spring what kind of objects I will be adding to the list. Thanks! – sharma sharma Aug 01 '13 at 22:19
  • I tried it out and turns out I don't have to specify the class type. – sharma sharma Aug 01 '13 at 22:33
  • could you please elaborate – jmj Aug 01 '13 at 22:40
  • I added this line and did not have to specify what type of list I a am using in the class. It works for List or List `` – sharma sharma Aug 01 '13 at 23:27