1

I need to define multiple configuration blocks in a single .properties file in Spring. Currently I am having multiple .properties file like below:

one.properties:

publishing.channel=ftp
ftp.user=user1
ftp.password=pass1
ftp.host=abc.xyz.com
ftp.port=21

two.properties

publishing.channel=ftp
ftp.user=user2
ftp.password=pass2
ftp.host=def.xyz.com
ftp.port=21

What I now require is defining only one .properties file and add all the configuration blocks in it like so:

publishing.channel=ftp
ftp.user=user1
ftp.password=pass1
ftp.host=abc.xyz.com
ftp.port=21

then another one

publishing.channel=ftp
ftp.user=user2
ftp.password=pass2
ftp.host=cdf.xyz.com
ftp.port=21

it could be http too

publishing.channel=http
http.user=user2
http.password=pass2
http.host=cdf.xyz.com

Problem is when I put multiple property blocks like this, I cannot differentiate in code as my bean methods (e.g. getHost()) will only fetch the last declared one in the properties file. I do not want to create many variables like host1, host2, host3 and so on as it would need to be modified in case there is another block of properties added. How can I make it generic?

Thanks in advance.

Bilal Shah
  • 1,135
  • 7
  • 17
  • 42
Hemang
  • 390
  • 3
  • 20
  • This might be the solution to your problem http://stackoverflow.com/questions/10433186/how-to-read-multiple-properties-having-the-same-keys-in-spring – Bilal Shah Nov 27 '15 at 06:45
  • Personally, i prefer to use structured configuration format for such cases, f.i. XML or JSON – Anton Afanasjew Nov 27 '15 at 06:54
  • @Bilal: Thanks for suggestion,but this solution uses multiple properties files and reads same keys without ambiguity. What I am looking for is to have only one properties file in the source and read same keys with different values based on some criteria. – Hemang Nov 27 '15 at 06:56

1 Answers1

0

You can use PropertiesConfiguration from Apache Commons Configuration and then access all the values of same key and add your logic to get the required value.

Use getStringArray(key) method or getList(key) method to access all values.

Bilal Shah
  • 1,135
  • 7
  • 17
  • 42
  • @Hemang Your property file is invalid. Keys must be unique. You should redisgn it or else you have to write you own method using solution stated in answer or something like that. – Bilal Shah Nov 27 '15 at 07:07
  • This is not my property file. I am aware the keys must be unique. Currently that is how my multiple properties files are, and now I want to combine them into one, so in case I need to change the configuration I only have to add/edit the config blocks and not change the code. – Hemang Nov 27 '15 at 07:14