您可以使用屬性這樣有資格。
在下面的代碼,你可以有
key=value
爲默認值,就像你現在做的和
key.ENVIRON=value
,如果它需要針對不同環境。如您所見,代碼非常短,並且它允許輕鬆比較不同的配置,因爲它們都在同一個位置。
如果您有複雜的系統,您可以使用ENVIRON.TYPE.INSTANCE擴展此方法。
public class EnvironProperties extends Properties {
private final String environ;
public EnvironProperties(String environ) {
this.environ = environ;
}
@Override
public String getProperty(String key) {
String property = super.getProperty(key + "." + environ);
return property == null ? super.getProperty(key) : property;
}
public String getEnviron() {
return environ;
}
public static void main(String... args) throws IOException {
String properties = "lock-timeout=7200000\n" +
"usesLogin=true\n" +
"uses-hardlocks=false\n" +
"use-nested-roles=1\n" +
"\n" +
"# Password Change URL for VSRD, VSRT and VSRP (in that order)\n" +
"pwchange-url=https://iteodova-md.dev.fema.net/va-npsc/pwchange/default.asp\n" +
"pwchange-url.PROD=https://iteodova-md.fema.net/va-npsc/pwchange/default.asp\n" +
"\n" +
"# Database Connectivity and User Session Management\n" +
"\n" +
"jdbc-driverClassName=oracle.jdbc.driver.OracleDriver\n" +
"jdbc-url.TEST=jdbc:oracle:thin:@wnli3d3.fema.net:1521:vsrd\n" +
"jdbc-url.DEV=jdbc:oracle:thin:@wnli3d2.fema.net:1521:vsrt\n" +
"jdbc-url.PROD=jdbc:oracle:thin:@mwli3d1.fema.net:1521:vsrp\n" +
"jdbc-url=jdbc:oracle:thin:@wnli3d4.fema.net:1521:vsrp";
EnvironProperties dev = new EnvironProperties("DEV");
EnvironProperties test = new EnvironProperties("TEST");
EnvironProperties prod = new EnvironProperties("PROD");
for (EnvironProperties ep : new EnvironProperties[]{dev, test, prod}) {
System.out.println("[" + ep.getEnviron() + "]");
ep.load(new StringReader(properties));
for (String prop : "uses-hardlocks,pwchange-url,jdbc-url".split(","))
System.out.println(prop + "= " + ep.getProperty(prop));
}
}
}
2015年的文件位置:https://commons.apache.org/proper/commons-configuration/ –