java - 如何在运行时更改属性文件并刷新配置类?

标签 java spring spring-mvc

我有properties文件在 classpathconfiguration classjava它映射此属性文件。当我更改属性文件时,我想刷新 configuration class也需要新值,我想在不重新启动的情况下完成此操作 server ,有什么解决办法吗?我该怎么办?我正在使用spring mvc

最佳答案

您应该使用@RefreshScope

文档:

A Spring @Bean that is marked as @RefreshScope will get special treatment when there is a configuration change. This addresses the problem of stateful beans that only get their configuration injected when they are initialized. For instance if a DataSource has open connections when the database URL is changed via the Environment, we probably want the holders of those connections to be able to complete what they are doing. Then the next time someone borrows a connection from the pool he gets one with the new URL.

The RefreshScope is a bean in the context and it has a public method refreshAll() to refresh all beans in the scope by clearing the target cache. There is also a refresh(String) method to refresh an individual bean by name. This functionality is exposed in the /refresh endpoint (over HTTP or JMX).

并像这样使用:

@Configuration
@PropertySource("classpath:configprops.properties")
@RefreshScope
public class ConfigProperties {
    // previous code
}

关于java - 如何在运行时更改属性文件并刷新配置类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51980932/

相关文章:

java - 将 python 转换为 java float 与 double

java - 在 ADF 中的弹出窗口焦点上设置 session 变量

java - 如何使用 thymeleaf 在具有动态列的数据表中显示输入值

java - 列索引超出范围,3 > 2。嵌套异常是 java.sql.SQLException :

java - Java EE 7 和 Java EE 6 之间的区别

java - 字符串的排列

java - 如何用 DefaultErrorHandler (spring-kafka) 替换已弃用的 SeekToCurrentErrorHandler?

Spring 批处理与 quartz 工作?

java - hibernate/jpa Autowire 注释产生 Nullpointer 异常错误

spring-mvc - SiteMesh 2.4.2 + Spring MVC 3.0.4-使用多个装饰器