Multiple properties files
In a java application, I am using .properties file to access application related config properties.
For eg.AppConfig.properties开发者_C百科
the contents of which are say,
settings.user1.name=userone
settings.user2.name=usertwo
settings.user1.password=Passwrd1!
settings.user2.password=Passwrd2!
I am accesing these properties through a java file - AppConfiguration.java
like
private final Properties properties = new Properties();
public AppConfiguration(){
properties.load(Thread.currentThread().getContextClassLoader()
.getResourceAsStream("AppConfig.properties"));
}
Now, instead of keeping all the key-value properties in one file, I would like to divide them in few files(AppConfig1.properties, AppConfig2.properties, AppConfig3.properties etc.).
I would like to know if it is possible to load these multiple files simultaneously.My question is not similar to - Multiple .properties files in a Java project
Thank You.
Yes. Simply have multiple load statements.
properties.load(Thread.currentThread().getContextClassLoader()
.getResourceAsStream("AppConfig1.properties"));
properties.load(Thread.currentThread().getContextClassLoader()
.getResourceAsStream("AppConfig2.properties"));
properties.load(Thread.currentThread().getContextClassLoader()
.getResourceAsStream("AppConfig2.properties"));
All the key-value pairs will be available to use using the properties object.
If I understand your question, you have two objectives in mind:
- Partition one very large .properties file into several smaller ones where the (key, value) pairs are related.
- Ensure that all .properties files are available at the same time, even if you read them simultaneously using threads.
If that's the case, I'd proceed with partitioning the .properties into several files and write a new class that handles the reading of individual .properties files and the merging of all the results into a single Properties instance.
As Properties
objects are in fact map, you can use all of their methods, including putAll(...)
. In your case, it would be useful to load each Property file using a separate Properties object, then merge them in your application properties.
I have 2 solutions for you:
- You can have different properties object for different properties files
You can merge them using
putAll()
.Properties properties1 = new Properties(); properties1.load(Thread.currentThread().getContextClassLoader() .getResourceAsStream("AppConfig1.properties")); Properties properties2 = new Properties(); properties.load(Thread.currentThread().getContextClassLoader() .getResourceAsStream("AppConfig2.properties")); Properties merged = new Properties(); merged.putAll(properties1); merged.putAll(properties2);
精彩评论