【问题标题】:How to manually reload properties file from Spring messageSource如何从 Spring messageSource 手动重新加载属性文件
【发布时间】:2016-04-04 02:02:42
【问题描述】:

对于 spring 框架,我想手动重新加载属性文件中的数据。实际上,当我手动运行这个 servlet 文件时,必须编写将手动重新加载数据的 reload servlet。

我已经为 messageSource 定义了 spring 配置。

<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"
        p:basename="classpath:/message" />

但不想在特定时间自动重新加载,例如可以在设置时自动重新加载:

<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"
            p:basename="classpath:/message"
            p:cacheSeconds="1" />

我之前尝试过 clearCaches() 但不是自动重载。

【问题讨论】:

    标签: java spring properties


    【解决方案1】:

    它现在正在工作。需要将 messageSource 注入 servlet 文件并调用 clearCache()。它确实会清除以前的属性数据并重新加载更新的属性文件。

    ReloadServlet.java

    ReloadableResourceBundleMessageSource rs = Global.getBean("messageSource", ReloadableResourceBundleMessageSource.class);
    rs.clearCache();
    

    Global.java中,

    private static ApplicationContext context;
    
    public static <T> T getBean(String s, Class<T> type) {
            return context.getBean(s, type);
    }
    

    谢谢。

    【讨论】:

      【解决方案2】:

      我不知道,你的意思是手动重新加载属性文件。 Spring 已经提供加载properties 文件如下。

      在你的 spring 配置文件中配置你的 properties 文件。例如。 applicationContext.xmlspring-beans.xml

      <util:properties id="MY_CONFIG" location="classpath:MY_CONFIG.properties"/>
      

      在你的 sping bean 中,如下注入

      @Resource(name = "MY_CONFIG")
      private Properties properties;
      

      您的 servlet 调用该 spring bean。

      更新

      如果您想直接从 Servlet 或其他类加载文件

      Load properties file in Servlet/JSP

      【讨论】:

      • “手动重新加载属性”意味着如果您在属性文件中添加新的 key=value 对,则无需重新部署此 Web 应用程序来更新您在属性文件中的更改。取而代之的是,编写新的 servlet 文件,注入消息源并手动运行此 servlet 以重新加载属性文件,该文件将更新我的更改而无需重新部署 Web 应用程序。
      • 我都试过了,演示。但不工作:)。对于 cacheSeconds 配置,它会在我们定义的每分钟自动重新加载。它会降低生产性能。这就是我在更改属性文件后发现手动重新加载的原因。
      • 您想要获取最新数据。但是,由于性能原因,您不想每分钟/秒重新加载一次。即使您使用某些 API 的FileChangeListener,此 API 也必须每分钟或每秒检查一次。
      猜你喜欢
      • 2018-04-18
      • 2012-10-26
      • 1970-01-01
      • 2019-09-12
      • 2017-01-16
      • 2017-11-17
      • 2014-11-26
      • 2023-03-31
      • 1970-01-01
      相关资源
      最近更新 更多