您可以通过这种方式将属性与资格一起使用。
在以下代码中,您可以拥有
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));
}
}
}