How to reload a @Value property from application.properties in Spring?

java, spring, spring-mvc

Solution

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 {
}

The instead of using @Value, each time you wanted the latest property you would use

environment.get("my.property");

Note

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.

Problem

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; ``` 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). But how?

Original source

Related problems