.properties as final static variable

时间:2016-04-15 14:51:15

标签: java properties

I've got a .properties in my java project, that is updated by shell script. I want to get this properties values and use it as final static variable. Here is my .properties code

 WEBURL=http://popgom.fr
 NODEURL=http://192.168.2.30:5555/wd/hub

I know I can get and use my .properties using this :

Properties prop = new Properties();
InputStream input = new FileInputStream("config.properties");
// load a properties file
prop.load(input);

String urlnode = prop.getProperty("NODEURL");

What I want to do is to get this String in every class of my project, without adding the code bellow in every classes.

How can I do this ? I've try to do an Interface, without success.

Any of you have an idea ?

Thanks for help

1 个答案:

答案 0 :(得分:1)

you can do it using Singleton pattern:

Example:

public class MyProperties{
   private static MyProperties instance = null;
   private Properties prop;

   private MyProperties() {
      InputStream input = new FileInputStream("config.properties");
      // load a properties file
      prop.load(input);

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

   public Properties getProperty() {
       return prop;
   }
}

You can invoke this code everywhere:

....
....
MyProperties.getInstance().getProperty();
....
....