在很多框架中,经常看到xml中将某个属性的值用{}代替的变量,并在properties文件中配置成键-值对表示,如图所示:
<dataSource type="SIMPLE">
<property name="JDBC.Driver" value="${jdbc.driver}" />
<property name="JDBC.ConnectionURL" value="${jdbc.connectionURL}" />
<property name="JDBC.Username" value="${username}" />
<property name="JDBC.Password" value="${password}" />
</dataSource>
properties文件:
jdbc.driver = com.mysql.jdbc.Driver
jdbc.connectionURL = jdbc:mysql://localhost:3306/pretty
username =root
password =root
ibatis中解析的方法:
public static String parsePropertyTokens(String string, Properties variables) {
final String OPEN = "${";
final String CLOSE = "}";
String newString = string; //name = ${username}
if (newString != null && variables != null) {
int start = newString.indexOf(OPEN);
int end = newString.indexOf(CLOSE);
while (start > -1 && end > start) { //迭代从已经检查过的开始
String prepend = newString.substring(0, start); // name=
String append = newString.substring(end + CLOSE.length()); //"" }后半部分
String propName = newString.substring(start + OPEN.length(), end); //username
String propValue = variables.getProperty(propName); //获取property的值
if (propValue == null) {
newString = prepend + propName + append; //如果没有从properties文件中取到值,直接返回变量的值
} else {
newString = prepend + propValue + append;
}
start = newString.indexOf(OPEN); //记录当前的${位置
end = newString.indexOf(CLOSE);
}
}
return newString; //如果properties为null,直接返回了传入的Strin
ibatis是这样解析的吗,来,咱们试一下:
public static void main(String[] args){
String username = "name=${username}";
InputStream is = NodeletUtils.class.getResourceAsStream("sys.properties");
Properties ps = new Properties();
try {
ps.load(is);
String result = parsePropertyTokens(username, ps);
System.out.println(result);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}