表明PropertyPlaceholderConfigurer是承擔properties讀取任務的類。
下面的類繼承PropertyPlaceholderConfigurer,通過重寫processProperties方法把properties暴露出去了。
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
public class CustomizedPropertyConfigurer extends PropertyPlaceholderConfigurer {
private static Map<String, Object> ctxPropertiesMap;
@Override
protected void processProperties(ConfigurableListableBeanFactory beanFactory,
Properties props)throws BeansException {
super.processProperties(beanFactory, props);
//load properties to ctxPropertiesMap
ctxPropertiesMap = new HashMap<String, Object>();
for (Object key : props.keySet()) {
String keyStr = key.toString();
String value = props.getProperty(keyStr);
ctxPropertiesMap.put(keyStr, value);
}
}
//static method for accessing context properties
public static Object getContextProperty(String name) {
return ctxPropertiesMap.get(name);
}
}
這樣此類即完成了PropertyPlaceholderConfigurer的任務,同時又提供了上下文properties訪問的功能。
於是在Spring配置文件中把PropertyPlaceholderConfigurer改成CustomizedPropertyConfigurer
<!-- use customized properties configurer to expose properties to program -->
<bean id="configBean"
class="com.payment.taobaoNavigator.util.CustomizedPropertyConfigurer">
<property name="location" value="classpath:dataSource.properties" />
</bean>
最後在程序中我們便可以使用CustomizedPropertyConfigurer.getContextProperty()來取得上下文中的properties的值了。
#生成文件的保存路徑
file.savePath = D:/test/
#生成文件的備份路徑,使用後將對應文件移到該目錄
file.backupPath = D:/test bak/
ConfigInfo.java 中對應代碼:
@Component("configInfo")
public class ConfigInfo {
@Value("${file.savePath}")
private String fileSavePath;
@Value("${file.backupPath}")
private String fileBakPath;
public String getFileSavePath() {
return fileSavePath;
}
public String getFileBakPath() {
return fileBakPath;
}
}
業務類bo中使用註解注入ConfigInfo對象:
@Autowired
private ConfigInfo configInfo;
需在bean.xml中添加組件掃描器,用於註解方式的自動注入:
<context:component-scan base-package="com.my.model" />