如何从Spring中的application.properties重新加载@Value属性? [英] How to reload a @Value property from application.properties in Spring?
问题描述
我有一个 spring-boot
应用程序。在run文件夹下,还有一个额外的配置文件:
I have a spring-boot
application. Under the run folder, there is an additional config file:
dir / config / application.properties
当应用程序启动时,它会使用文件中的值并将它们注入:
When the applications starts, it uses the values from the file and injects them into:
@Value("${my.property}")
private String prop;
问题:如何触发重新加载 @Value
属性?
我希望能够在运行时更改 application.properties
配置,并拥有 @Value
字段已更新(可能通过在应用程序内调用 / reload
servlet来触发更新)。
Question: how can I trigger a reload of those @Value
properties?
I want to be able to change the application.properties
configuration during runtime, and have the @Value
fields updated (maybe trigger that update by calling a /reload
servlet inside the app).
但如何?
推荐答案
使用下面的bean每1秒重新加载config.properties。
Use the below bean to reload config.properties every 1 second.
@Component
public class PropertyLoader {
@Autowired
private StandardEnvironment environment;
@Scheduled(fixedRate=1000)
public void reload() throws IOException {
MutablePropertySources propertySources = environment.getPropertySources();
PropertySource<?> resourcePropertySource = propertySources.get("class path resource [config.properties]");
Properties properties = new Properties();
InputStream inputStream = getClass().getResourceAsStream("/config.properties");
properties.load(inputStream);
inputStream.close();
propertySources.replace("class path resource [config.properties]", new PropertiesPropertySource("class path resource [config.properties]", properties));
}
}
您的主配置如下所示:
@EnableScheduling
@PropertySource("classpath:/config.properties")
public class HelloWorldConfig {
}
而不是使用@Value,每次你想要使用最新的属性时
The instead of using @Value, each time you wanted the latest property you would use
environment.get("my.property");
这篇关于如何从Spring中的application.properties重新加载@Value属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!