在Spring的衆多功能中,有一個幫助類PropertyPlaceholderHelper,專門負責解析路徑中或者名字中含有占位符的字串,并負責填充上具體的值。
public String replacePlaceholders(String value, final Properties properties) {
Assert.notNull(properties, "Argument 'properties' must not be null.");
return replacePlaceholders(value, new PlaceholderResolver() {
public String resolvePlaceholder(String placeholderName) {
return properties.getProperty(placeholderName);
}
});
}
例舉一個例子:
public static void main(String[] args) throws Exception {
Properties p = System.getProperties();
p.setProperty("name", "be");
ApplicationContext factory = new ClassPathXmlApplicationContext("classpath:${name}ans.xml");
LoggingBean lb = (LoggingBean) factory.getBean("logging");
lb.run();
BeanDestried sd = (BeanDestried)factory.getBean("beanDestried");
sd.run();
//print();
}
這樣占位符就換成了 我們想要的内容。其實在真正的配置檔案中,此種問題很普遍,但是歸根結底,還是需要這個幫助類來處理。