【问题标题】:how can I reload/refresh properties in spring at runtime without jvm restart?如何在运行时在 spring 中重新加载/刷新属性而不重新启动 jvm?
【发布时间】:2013-08-28 18:23:52
【问题描述】:

如何在运行时在 spring 中重新加载/刷新属性而不重启 jvm?

我正在寻找一些优雅的东西,它应该适用于 Prod。因此,我猜 JRebel 已经不在了。

目前,我在 MYProject.properties 中有我的属性

oms.url=abbc.com
checkin.enabled=true

并且我的 java 文件会自动连接以从 applicationContext 提供的不同属性文件中搜索和使用这些属性:

<bean id="applicationProperties" class="myproject.config.CustomPropertyPlaceHolder">
        <property name="ignoreResourceNotFound" value="true" />
        <property name="locations">
            <list>
                <value>classpath:MyProject.properties</value>
                <value>file:${CATALINA_BASE}/lib/MyProject.properties</value>
                <!--<value>file:///appl/conf/outlet.properties</value>-->
                <value>classpath:db.password</value>
                <value>file:${CATALINA_BASE}/lib/db.password</value>
                <!-- <ref bean="applPropertiesFromDb" /> -->
            </list>
        </property>
    </bean>

Java 文件为:

@Value("${checkin.enabled}")
    private String checkinEnabled;

【问题讨论】:

  • 据我所知 Spring 属性解析为 java final 静态变量,因此一旦实例化它们就无法在没有 jvm 重启的情况下更改。
  • 它不完全是 spring 属性,而更像是一个容器在启动时初始化的 Bean。
  • 取决于 bean 的性质。如果就像在您的示例中一样,并且它初始化与 DB 的连接,即使 bean 被重新配置,那么旧连接会发生什么?在内部,Spring bean 有一个可以重新启动的生命周期,很难说它是可能的,而不会对框架代码进行服务器入侵。也许寻找一些 JMX 功能?
  • @AntonArhipov:是的,我也研究了 JMX 选项。但是面临的限制是,使用 JMX,我将不得不手动加载所有属性,并且我不再使用注释:
  • @AshishGarg 啊,是的。我认为,使用注释几乎没有机会。

标签: java spring refresh reload applicationcontext


【解决方案1】:

考虑像这样实现 MessageSource Spring bean:
1.更新applicationContext.xml

<bean id="messageSource" class="com.mycompany.service.DynamicMessageSource" />

2.编写自己的MessageSource实现

public class DynamicMessageSource extends AbstractMessageSource {

    // Autowire propertiesService

    @Override
    protected MessageFormat resolveCode(String code, Locale locale) {
        String result = propertiesService.getProperty(code);
        return new MessageFormat(result, locale);
    }
}

3.实现您的自定义服务以从某个位置(数据库、属性文件等)读取属性。
4.在更新属性源时享受属性的动态更新。

【讨论】:

    【解决方案2】:

    使用ReloadableResourceBundleMessageSource

    但这不会被刷新。

    private String checkinEnabled;
    

    您必须重新加载checkinEnabled 变量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-12
      • 1970-01-01
      • 2019-05-06
      • 2014-10-23
      • 2018-10-13
      • 1970-01-01
      相关资源
      最近更新 更多