如何从 Spring 中的 application.properties 重新加载 @Value 属性? [英] How to reload a @Value property from application.properties in Spring?

查看:47
本文介绍了如何从 Spring 中的 application.properties 重新加载 @Value 属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 spring-boot 应用程序.在运行文件夹下,还有一个额外的配置文件:

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));
    }
}

您的主要配置将类似于:

Your main config will look something like :

@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");

注意

虽然示例中的 config.properties 取自类路径,但它仍然可以是已添加到类路径中的外部文件.

Although the config.properties in the example is taken from the classpath, it can still be an external file which has been added to the classpath.

这篇关于如何从 Spring 中的 application.properties 重新加载 @Value 属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆