How to make a variable / constant available all the time once initialized?

advertisements

I've a swing application that has to connect to database for some resources, for this i used .properties file to store database properties and that can be read at runtime.
For this i am using the following code

    public void readPropertiesFile(){
       try{
         InputStream is = ReadValues.class.getResourceAsStream(PROP_FILE);
         Properties prop = new Properties();
         prop.load(is);
         String URL = prop.getProperty("DB_URL");
         String user = prop.getProperty("DB_USER");
         String  pwd = prop.getProperty("DB_PWD");
         is.close();
      /* code to use values read from the file*/
       }catch(Exception e){
         System.out.println("Failed to read from " + PROP_FILE + " file.");
       }
   }

but i've to call this method whenever i want to connect to the database (for Connection object). I know the thing that now processing is fast enough to run these lines in micro seconds, but it's for my own knowledge that suggest me the ways through which i can store these DB values when application starts or the first time user try to connect to DB for any operation in such objects or variables or constants that will be usable until the application restarts and can be called directly without reading the file.

P.S. : I know that the DB values will not change oftentimes, and if it happens than i'll be happy to restart my application :)


by making these static fields in a separate class, they will not be loaded until the first time you access URL,USER, or PASSWORD.

public class DbProps {
  public static final String URL;
  public static final String USER;
  public static final String PASSWORD;

  static {
       try{
         InputStream is = ReadValues.class.getResourceAsStream(PROP_FILE);
         try {
           Properties prop = new Properties();
           prop.load(is);
           URL = prop.getProperty("DB_URL");
           USER = prop.getProperty("DB_USER");
           PASSWORD = prop.getProperty("DB_PWD");
         } finally {
           is.close();
         }
       }catch(Exception e){
         throw new RuntimeException("Failed to read from " + PROP_FILE + " file.", e);
       }
  }
}