Managing configurations in java (initial config /

2019-03-03 09:20发布

I got a class Config wich looks like that:

public Class Config {

    public static int someIntValue = 0;
    public static String someText = "some text";

}

What i want to do now is saving and loading that config and there is also that inital config if there is no need to load another. So the config can change at any point in the programm.

What i came up with was a Singelton like pattern

public Class Config {

    public static Config instance;

    private int someIntValue = 0;
    private int String someText = "some text";

    public static Config getInstance(){
    if(instance == null)
    instance = new Config();
    return instance;
    }

    public void setInstance(Config config){
    this.instance = config;
    }
    //getter/setter
    ...

}

But in the end it doesnt look like the best approach and im not quite happy with it :/ Maybe you guys can help me out with a usual / "best practice" way to do that.

Best Regards Made

3条回答
smile是对你的礼貌
2楼-- · 2019-03-03 10:08

I would just use java.util.Properties, or some wrapper around it. Another good approach is java bean and something like xstream to save/load stuff.

查看更多
放荡不羁爱自由
3楼-- · 2019-03-03 10:08

Usually in Java for configuration use properties files. And then use ResuorseBundle for reading properties.

Your "singleton" is not a Singleton in the conventional sense. 1) Field instance must be private 2) Remove SetInstance method 3) And you should make your singleton thread safe.

查看更多
Rolldiameter
4楼-- · 2019-03-03 10:08

If you'd consider avoiding writing the boilerplate code around java.util.Properties, you can have a look at something that does it for you: OWNER API.

It's configurable to tailor your needs and it offers some additional neat features if compared to java.util.Properties (read the docs).

Example. You define an interface with your configuration parameters:

public interface ServerConfig extends Config {
    int port();
    String hostname();
    @DefaultValue("42")
    int maxThreads();
    @DefaultValue("1.0")
    String version();
}

Then you use it like this:

public class MyApp {
    private static ServerConfig cfg = ConfigFactory.create(ServerConfig.class);
    private MainWindow window;

    public MyApp() {
       // you can pass the cfg object as dependency, example:
       window = new MainWindow(cfg);
    }

    public void start() {
       window.show();
    }

    public static void main(String[] args) {
       // you can use it directly,  example:
       System.out.println("MyApp version " + cfg.version() + " copyright (c) ACME corp.");
       MyApp app = new MyApp();
       app.start();
    }
}

You can define the cfg object as member instance on the classes where you need, or you can pass the instance to constructors and methods where you need it.

Version 1.0.4 will be released soon and it will include also "hot reload" and many improvements.

查看更多
登录 后发表回答