Managing configurations in java (initial config / save/load config)

青春壹個敷衍的年華 提交于 2019-12-02 06:34:53

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.

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!