1

这是我的弹簧配置文件:

   <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>

和代码:

 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());

我希望输出为:

Controller1
Controller1 changed!

但它是

Controller1
Controller1

除了将 Controller 注入 Controller1 之外,还有更简单的方法来获取更新的值吗?

谢谢你。

4

1 回答 1

0

将属性定义 message为 bean 它自己

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

并改变原来的bean配置

   <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>

现在将 java 代码中的消息更改为

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

并将其添加回上下文

于 2013-08-01T21:47:44.400 回答