Abhishek Honey
Abhishek Honey

Reputation: 645

Read properties from properties file in a regular interval at runtime

There are some properties, and I want to read these properties in an interval, and if there is any update in the properties, I am taking some action on that basis.

    @Value("${sms.smpp.country.list:{}}")
    private String smppCountryList;

    @Value("${sms.smpp.country.config.list:{}}")
    private String smppCountryConfigList;

    @Value("${sms.smpp.properties.file.location:{}}")
    private String propertiesFileLocation;
     

I have written a code to read the properties using cron, here is the code.

    @Scheduled(cron = "0 0/7 * * * ?")
    public Properties readPropertiesFile() {
        Properties prop = null;
        
        try (InputStream input = new FileInputStream(propertiesFileLocation)) {
            prop = new Properties();
            prop.load(input);
        } catch (IOException ex) {
            logger.info("[SMPP] [CONFIG CRON] Exception occurred while reading the properties file: [{}]",ex.getMessage());
        }
        
        return prop;
    }

The code is getting called by the cron, or I can also write an onFileChangeHandler on the file.

But is there any easy and elegant way to do this, like can this be handled by spring?

Upvotes: 0

Views: 309

Answers (2)

Artem
Artem

Reputation: 406

You have to use Spring Config Server and if you want to update property annotated with @Value, you need to annotate the class with @RefreshScope.

Upvotes: 1

Shivendra Tiwari
Shivendra Tiwari

Reputation: 229

Edit 1: Looking at your code i want to point one thing that @Value variables won't be updated with updated value even if you continuously run cron job

If you regularly want to look for configuration changes Spring Boot comes with a spring config server.

Your micro service will be up to date with the configuration without writing any lines to code.

Have a look a Spring Cloud Config Server

Upvotes: 1

Related Questions