Spring配置 在xml和java程式碼中讀取properties檔案
阿新 • • 發佈:2019-01-11
在spring引入屬性檔案
<bean id="propertyConfigurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <!-- 這裡支援多種定址方式:classpath和file --> <value>classpath:redis.properties</value> <value>classpath:config.properties</value> </list> </property> </bean> <!-- 重寫propertyConfigurer 主要是為了在java程式碼中獲取屬性 --> <bean id="gloal" class="com.baojing.wx.config.Gloal"> <property name="location"> <value>classpath:gloal.properties</value> </property> </bean>
第一種方案直接在xml直接${key}就能獲取到property中的值。
第二種的原理是整合繼承
org.springframework.beans.factory.config.PropertyPlaceholderConfigurer類。
public class Gloal extends PropertyPlaceholderConfigurer{ private staticMap<String,String> propertyMap; @Override protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException { super.processProperties(beanFactoryToProcess, props); propertyMap = new HashMap<String, String>(); for (Object key : props.keySet()) { String keyStr = key.toString(); String value = props.getProperty(keyStr); propertyMap.put(keyStr, value); } } //static method for accessing contextproperties public static String getProperty(String name) { return propertyMap.get(name); } }
使用Gloal.getProPerty(Key)獲取value