如何在Spring中更新@Autowired String bean的值? [英] How do I update the value of an @Autowired String bean in Spring?

查看:357
本文介绍了如何在Spring中更新@Autowired String bean的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个String,我将自动装配为bean。 String 的值是通过属性文件设置的,并在运行时加载。我可以验证这一点。这是我的XML:

I have a String that I'm autowiring as a bean. The value for the String is set via a properties file, and is loaded at runtime. That much I can verify. Here's my XML:

<context:property-placeholder location="classpath:my-app.properties" />

<bean id="loadedProp" class="java.lang.String">
   <constructor-arg>
      <value>${loaded-prop}</value>
   </constructor-arg>
</bean>

在我的应用程序中,我在bean中自动装配:

And in my application, I autowire in the bean:

@Component
public class Foo {

  @Autowired
  private String loadedProp;
}

一切都很有效。我有多个组件在这个bean中自动装配。我正在尝试做的是,在应用程序运行时,将bean的值更新为其他内容,以便在bean自动装配的任何地方,它使用最新的值。是否可以这样做,或者我只是需要在每次想要更改值时重新启动?

Everything works dandy. I have multiple components that autowire in this bean. What I'm trying to do is, while the application is running, update the value of the bean to be something else, so that everywhere the bean is autowired in, it uses the most up to date value. Is it possible to do this, or do I just need to restart everytime I want to change the value?

推荐答案

阅读完之后很少有其他答案和评论,我能够找到解决方案。我最终创建了一个简单的类:

After reading a few of the other answers and comments, I was able to figure out a solution. I ended up creating a simple class:

public class LPropBean {

   private String loadedProp;

   public LPropBean(String loadedProp) {
       this.loadedProp = loadedProp;
   }

   // getters and setters...
}

我更新了我的XML文件:

I updated my XML file:

<bean id="lPropBean" class="LPropBean">
  <constructor-arg>
    <value>${loaded-prop}</value>
  </constructor-arg>
</bean>

并更新了所有 @Component s bean中的autowire:

And updated all of the @Components that autowire in the bean:

@Autowire
private LPropBean lPropBean;

// ... later ...
lPropBean.setLoadedProp(newProp);

// ... later ...
lPropBean.getLoadedProp();

我确信有更优雅的方式,但这正是我需要它的方式。

I'm sure there is a more elegant way, but this worked exactly how I needed it to.

这篇关于如何在Spring中更新@Autowired String bean的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆