It is necessary that when repeatedly calling the getProperty method, it does not constantly read the file by key value, but did it once and then worked with this value from memory.

 public class PropertiesLoaderImpl implements PropertiesLoader { public static Properties properties; @Override public String getProperty(String propertyName) { properties = new Properties(); try { FileInputStream file = new FileInputStream("src/main/resources/config.properties"); properties.load(file); return properties.getProperty(propertyName); } catch (IOException e) { e.printStackTrace(); } return null; } } 

How correct is this decision, will it constantly read the file every time it is accessed or once?

    1 answer 1

    In this implementation, the value is read from the file each time the method is called.

    To read a file once, for example, you can use null check for the properties field ( lazy initialization ):

     public class PropertiesLoaderImpl implements PropertiesLoader { public static Properties properties; @Override public String getProperty(String propertyName) { if (properties == null) { properties = new Properties(); try (FileInputStream file = new FileInputStream("src/main/resources/config.properties")) { properties.load(file); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return properties.getProperty(propertyName); } } 

    or static initialization block:

     public class PropertiesLoaderImpl implements PropertiesLoader { public static Properties properties; static { properties = new Properties(); try (FileInputStream file = new FileInputStream("src/main/resources/config.properties")) { properties.load(file); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } @Override public String getProperty(String propertyName) { return properties.getProperty(propertyName); } }