如何在运行时使用 spring 从属性文件中获取键值

How to get key value from properties file at runtime using spring

我想在运行时从属性文件中获取更改后的键值。

test.properties 文件: 名字=嗨

我已经让线程休眠了 5 秒,并将键值更改为 "Hello",但它没有得到更改。

<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>classpath:test.properties</value>
        </list>
    </property> 
    <property name="ignoreResourceNotFound" value="true" />
    <property name="ignoreUnresolvablePlaceholders" value="true" />
</bean>

<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basenames">
        <list>
            <value>classpath:test</value>
        </list>
    </property>
    <property name="cacheSeconds" value="1" />
</bean>

<bean id="tempBean" name="tempBean1" class="org.sri.spring.temp.Temp"
    lazy-init="false" scope="prototype">
    <constructor-arg type="String" value="${name}" />
</bean> 

我认为 Spring 不会在属性更改时更新已经存在的 bean。

尝试创建一个新bean(原型作用域)

XML 配置中的 ${name} 占位符使用 PropertySourcesPlaceholderConfigurer 解析,您可能会注意到,nothing 是共同点使用您的可重新加载 messageSource。 这两种方式都行不通,因为 Spring 仅实例化 tempBean 一次:在应用程序启动时,通过将 ${name} 的值传递给构造函数。 bean 本身并不知道值的来源(特别是,它不关心属性文件是否被编辑)。

如果你真的认为这样做是个好主意†,你可以将整个messageSource注入你的tempBean,并得到当前每次调用的值,例如:

public class Temp {
  @Autowired // or wired in XML, constructor, etc.
  private MessageSource messages;

  public String sayHello() {
    return messages.getMessage("name", null, Locale.getDefault());
  }
}

† 注入与配置相关的对象会使测试更加困难,并且可以说是糟糕的设计(混合问题)。看看 Spring Cloud Config 项目,因为这很可能就是未来的样子。