Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 573
membersound Avatar asked Oct 27 '16 14:10

membersound


People also ask

How do I refresh application properties in spring boot?

For Reloading properties, spring cloud has introduced @RefreshScope annotation which can be used for refreshing beans. Spring Actuator provides different endpoints for health, metrics. but spring cloud will add extra end point /refresh to reload all the properties.

How do I load two properties in spring?

To add different files you can use the spring. config. location properties which takes a comma separated list of property files or file location (directories). The one above will add a directory which will be consulted for application.

Can we update application properties in spring boot?

You can do something like reading the properties file using FileInputStream into a Properties object. Then you will be able to update the properties.


1 Answers

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.

like image 94
Essex Boy Avatar answered Sep 22 '22 09:09

Essex Boy