Pat
Pat

Reputation: 2238

How do I update the value of an @Autowired String bean in Spring?

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>

And in my application, I autowire in the bean:

@Component
public class Foo {

  @Autowired
  private String loadedProp;
}

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?

Upvotes: 12

Views: 13057

Answers (3)

Pat
Pat

Reputation: 2238

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

I updated my XML file:

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

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.

Upvotes: 5

Alberto Gutierrez
Alberto Gutierrez

Reputation: 1588

Every time you want to change your spring injected values through changing the configuration, you are going to have to restart your container, which usually involves restarting your server.

Upvotes: 0

nicholas.hauschild
nicholas.hauschild

Reputation: 42834

Since String is immutable, you cannot just change its underlying value and have everyone that has a reference to it be updated.

You can change the reference of the String that an instance of Foo is holding onto to point to a different String, but it will only be realized by objects that are working with the specific Foo you updated. If Foo is a Spring singleton, this shouldn't be an issue though...

Upvotes: 3

Related Questions