Make Java Properties available across classes?

前端 未结 8 2230
情深已故
情深已故 2020-12-30 08:16

I chose to take properties file for customization of some settings. I use the following code to make a Properties Object available in a class

Properties defa         


        
8条回答
  •  鱼传尺愫
    2020-12-30 08:44

    Once you initialized defaultProps, you can make its contents available to other objects in your app e.g. via a public static accessor method, e.g.:

    public class Config {
      private static Properties defaultProps = new Properties();
      static {
        try {
            FileInputStream in = new FileInputStream("custom.properties");
            defaultProps.load(in);
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
      }
      public static String getProperty(String key) {
        return defaultProps.getProperty(key);
      }
    }
    

    This is the simplest approach, however it creates an extra dependency which makes unit testing harder (unless you provide a method in Config to set a mock property object for unit testing).

    An alternative is to inject defaultProps (or individual configuration values from it) into each object which needs it. However, this may mean you need to add extra parameter(s) to lots of methods if your call hierarchies are deep.

提交回复
热议问题