简体   繁体   中英

How to set bean property to property of another bean

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM