Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change values and then save it in the config. #93

Closed
spideynn opened this issue Sep 2, 2014 · 2 comments
Closed

Change values and then save it in the config. #93

spideynn opened this issue Sep 2, 2014 · 2 comments
Labels

Comments

@spideynn
Copy link

spideynn commented Sep 2, 2014

Hi,
Is it possible to change the config value while the application is running and then save the config with the changed value? (If it is then I didn't see it in the docs)

@lviggiano
Copy link
Collaborator

Hi.

This use case can be covered by Accessible and Mutable interfaces.

To change properties of a Config object, you can use the Mutable interface.

Example:

     public interface MyConfig extends Config, Mutable {
         @DefaultValue("18")
         int minAge();
     }

     public void example() {
         MyConfig cfg = ConfigFactory.create(MyConfig.class);
         int before = cfg.minAge();                 // before = 18
         int old = cfg.setProperty("minAge", "21"); // old = 18
         int after = cfg.minAge();                  // after = 21
         int old2 = cfg.removeProperty("minAge");   // old2 = 21
         int end = cfg.minAge();                    // end = null
     }

Once the cfg object is updated in memory you can dump it to the filesystem using method store() exposed by the Accessible interface

Some time ago, someone asked a "smart properties save method" (see #16), unfortunately it is not easy to implement it properly.

Alternatively...

If your properties file is stored on the file system you could change the properties file (something like this), then you use the hot reload feature to have your object automatically updated. Unfortunately this use case is not available inside the library yet, so you have to implement it by your own.

@spideynn spideynn closed this as completed Sep 9, 2014
@zygimantus
Copy link

zygimantus commented Mar 18, 2017

I found an easy solution like this:

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL url = classLoader.getResource("Config.properties");
onfig.store(new FileOutputStream(url.getFile()), "no comments");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants