Is there a way we can have conditional statement inside a .properties
file?
like:
if(condition1)
xyz = abc
else if(condition2)
xyz = efg
Is there a way we can have conditional statement inside a .properties
file?
like:
if(condition1)
xyz = abc
else if(condition2)
xyz = efg
No, it's not possible. The file format is freely available: http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html#load%28java.io.Reader%29.
Do this in Java code:
if (condition1) {
return properties.getProperty("xyz.1");
}
else if (condition2) {
return properties.getProperty("xyz.2");
}
No There is no such conditional statement in properties file, May be you would write a wrapper over Properties
to encapsulate your logic
Example:
class MyProperties extends Properties {
/**
*
*
*
* @param key
* @param conditionalMap
* @return
*/
public String getProperty(String key, List<Decision> decisionList) {
if (decisionList == null) {
return getProperty(key);
}
Long value = Long.parseLong(getProperty(key));
for (Decision decision : decisionList) {
if (Condition.EQUALS == decision.getCondition() && decision.getValue().equals(value)) {
return getProperty(decision.getTargetKey());
}
}
return super.getProperty(key);
}
}
and
enum Condition {
EQUALS, GREATER, LESSER
}
and
class Decision {
Condition condition;
String targetKey;
Long value;
//accessor
public Condition getCondition() {
return condition;
}
public void setCondition(Condition condition) {
this.condition = condition;
}
public String getTargetKey() {
return targetKey;
}
public void setTargetKey(String targetKey) {
this.targetKey = targetKey;
}
}
so now for example if you want to read the properties file, get category of age, if it is greater than 0 and less than 10 read kid
so may be you could pass the list of such conditions,
note: This design can go under much improvement (not good design), it is just to illustrate how to wrap properties and add stuff that OP wants
If your problem is different properties for different environments (e.g. devl, test, perf, prod), the common solution is a different version of the properties file for each environment. Communicate environment info to your app and look for a file with the correct name appended to the file name.
Something like this for Spring:
Environment-specific configuration for a Spring-based web application?
As @Jigar said, there is no conditional logic in a properties file. But you could have two lines in there, e.g. something like:
xyz.condition1 = abs
xyz.condition2 = efg
and, in your code to access the property, append the proper condition to the key.
this is the way:
xyz[condition1]=abs
xyz[condition2]=efg