在spring中提供了一個專門加載文件的類PropertyPlaceholderConfigurer,通過這個類我們只需要給定需要加載文件的路徑就可以
通過該類加載到項目,但是為了后面在程序中需要使用到屬性文件內容,在這里將加載到的配置文件全部保存進一個map對象中,后面可以直接
鍵值對去用:
首先創建一個繼承PropertyPlaceholderConfigurer的類PropertyConfigurer,加載文件,並保存進對象:
public class PropertyConfigurer extends PropertyPlaceholderConfigurer{ private static Map<String, Object> ctxPropertiesMap; @Override protected void processProperties( ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException { //spring載入配置文件(具體原理還在研究中) super.processProperties(beanFactoryToProcess, props); ctxPropertiesMap = new HashMap<String, Object>(); //便利加載的配置文件的鍵值,並根據鍵值獲取到value值,然后一同保存進map對象 for (Object key : props.keySet()){ String keyStr = key.toString(); String value = props.getProperty(keyStr); ctxPropertiesMap.put(keyStr, value); } } //此方法根據map對象的鍵獲取其value的值 public static Object getContextProperty(String name) { return ctxPropertiesMap.get(name); } }
然后在spring的配置文件中配置需要載入的屬性文件
<!--讀入配置文件,在后面的代碼中需要用到屬性文件的內容時 --> <bean id="propertyConfigurer" class="cn.com.owg.util.PropertyConfigurer"> <property name="locations"> <value>classpath*:jdbc.properties</value> </property> </bean>
<!--讀入配置文件,后面的代碼不需要用到屬性文件的內容時,直接通過PropertyPlaceholderConfigurer來載入屬性文件 -->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>classpath*:jdbc.properties</value>
</property>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean>
后面的代碼中需要使用屬性配置文件時:
String driverManager=PropertyConfigurer.getContextProperty("jdbc:driverClassManager")).trim();//獲取屬性文件的某一個內容