无需重新启动容器即可按需更改配置

时间:2017-10-04 18:46:19

标签: spring spring-mvc configuration

Spring MVC + Java 8 + Tomcat 8堆栈

我在yaml中维护我的配置并使用Spring PropertyPlaceholderConfigurer展平属性并在bean中维护配置。

今天,它有一个固有的问题,因为每当YML文件发生变化时我都需要重启服务器。

我相信有一些方法可以在不重启的情况下刷新bean,但我主要担心的是如何以失败安全的方式进行操作。

让我们假设,有一个请求,那个时候配置是A,然后我们刷新配置,现在它的B,但如果任何后续用户请求依赖于配置,那么它会爆炸。

1 个答案:

答案 0 :(得分:1)

将此配置添加到servlet-context.xml以动态捕获属性更改:

<context:property-placeholder
    location="file:${A_CONFIG_LOCATION}/configuration.properties" />

<beans:bean id="propertiesLoader"
    class="org.springframework.context.support.ReloadableResourceBundleMessageSource">

    <beans:property name="cacheSeconds" value="1" />
    <beans:property name="basenames">
        <beans:list>
            <beans:value>file:${A_CONFIG_LOCATION}/configuration
            </beans:value>
        </beans:list>
    </beans:property>
</beans:bean>

然后你可以读取这样的属性值:

@Component
public class PropertiesReader {

    private String  value         = "some_default_value";

    @Autowired
    MessageSource   propertiesLoader;

    public String getValue() {
        value = propertiesLoader.getMessage("configuration.value", null, null);
        return value;
    }


}
相关问题