我有properties
文件在 classpath
和configuration class
在java
它映射此属性文件。当我更改属性文件时,我想刷新 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/