简体   繁体   English

如何加载属性文件并将其传递给java单例(枚举)

[英]How do load a properties file and pass it to a java singleton (enum)

I have a java singleton class that has my application settings. 我有一个java单例类,它有我的应用程序设置。

I used this approach: What is an efficient way to implement a singleton pattern in Java? 我使用了这种方法: 在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: 我在/ WEB-INF /文件夹中创建了一个settings.properties文件,现在问题是我知道如何加载属性文件的唯一方法,它需要servlet上下文:

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? 那么这个属性文件是属性文件的静态表示吗? ie it is very fast and effecient? 即它是非常快速和有效的?

can you try putting your properties directly under src folder rather than WEB-INF folder? 你可以尝试将你的属性直接放在src文件夹而不是WEB-INF文件夹下吗?

WORKDIR
+ SRC
| + PACKAGES
| | + org.personal.foo  
| - system.properties
| + WEB-INF

Spring has facilities for exposing properties files as beans. Spring具有将属性文件公开为bean的功能。 You might wanna go that route, given that you tagged your post with "Spring". 鉴于您使用“Spring”标记了帖子,您可能想要走那条路。

Here's one guy's take on how to load properties files using Spring: 这是一个人如何使用Spring加载属性文件:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM