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

后端 未结 3 838
情歌与酒
情歌与酒 2021-02-14 00:07

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

相关标签:
3条回答
  • 2021-02-14 00:19

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

    0 讨论(0)
  • 2021-02-14 00:21

    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.

    0 讨论(0)
  • 2021-02-14 00:26

    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.

    0 讨论(0)
提交回复
热议问题