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

后端 未结 3 1967
自闭症患者
自闭症患者 2021-01-23 11:41

I got a class Config wich looks like that:

public Class Config {

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

}
         


        
相关标签:
3条回答
  • 2021-01-23 11:54

    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.

    0 讨论(0)
  • 2021-01-23 12:09

    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.

    0 讨论(0)
  • 2021-01-23 12:19

    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.

    0 讨论(0)
提交回复
热议问题