3

I have a java singleton class that has my application settings.

I used this approach: What is an efficient way to implement a singleton pattern in Java?

So I have:

public enum MySettings {

   INSTANCE;

   // bunch of private vars


   private MySettings {
     // load a json file and set my properties
     JsonParser parser = jf.createJsonParser(new File("HARD_CODED_PATH_HERE"));
   }

   // public getters/setters here


}

So the problem is the hard coded path I have currently.

I created a settings.properties file in my /WEB-INF/ folder, now the problem is the only way I know how to load a properties file, it requires the servlet context:

Properties prop = new Properties();
propertiesload(getServletContext().....);

Is there another way to load this?

So is this properties file a static representation of the properties file? i.e. it is very fast and effecient?

Community
  • 1
  • 1
Blankman
  • 259,732
  • 324
  • 769
  • 1,199

2 Answers2

1

can you try putting your properties directly under src folder rather than WEB-INF folder?

WORKDIR
+ SRC
| + PACKAGES
| | + org.personal.foo  
| - system.properties
| + WEB-INF
Em Ae
  • 8,167
  • 27
  • 95
  • 162
  • This would be a better answer if you explained (a) where the properties file would end up in the packaged WAR file, and (b) how you could load it in the code. – Tom Anderson Mar 15 '12 at 20:34
  • @TomAnderson I don't want the file embedded as a resource because that would be I would have to re-compile just to change a setting (rather that restarting tomcat). So it will be in plain text in the /web-inf folder. – Blankman Mar 15 '12 at 20:46
  • 1
    @Blankman: if your WAR is exploded, as it sounds like it is, you won't have to recompile. You can just change the file and restart. – Tom Anderson Mar 15 '12 at 20:50
  • @TomAnderson ah ok, sure that works. So how can I load it then? I don't have access to getServletContext() from inside of the singleton class, so what should I be doing? – Blankman Mar 15 '12 at 22:15
  • @Em that' doesnt' solve the problem with loading it, getServletContext is not available to me? – Blankman Mar 15 '12 at 22:15
  • 2
    @Blankman if the file is on the classpath, as it is here, then you can load it with [Class.getResourceAsStream](http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#getResourceAsStream%28java.lang.String%29). I was hoping Em Ae would point that out, but evidently not. – Tom Anderson Mar 17 '12 at 13:40
  • sorry guys, i was away. lost track if there was discussion going on. i guess @TomAnderson's answers would have solved your problem – Em Ae Mar 18 '12 at 01:12
1

Spring has facilities for exposing properties files as beans. You might wanna go that route, given that you tagged your post with "Spring".

Here's one guy's take on how to load properties files using Spring:

http://www.zparacha.com/how-to-read-properties-file-in-spring/#.T2JQqt5SRfQ

Marvo
  • 17,845
  • 8
  • 50
  • 74