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

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.