国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > Java > 正文

Spring用代碼來讀取properties文件實例解析

2024-07-13 10:16:18
字體:
來源:轉載
供稿:網友

有些時候,我們需要以Spring代碼直接讀取java/235787.html">properties配置文件,那么我們要如何操作呢?下面我們來看看具體內容。

我們都知道,Spring可以@Value的方式讀取properties中的值,只需要在配置文件中配置

org.springframework.beans.factory.config.PropertyPlaceholderConfigurer

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">    <property name="location">      <value>classpath:config.properties</value>    </property>  </bean>

那么在需要用到這些獲取properties中值的時候,可以這樣使用

  @Value("${sql.name}")  private String sqlName;

但是這有一個問題,我每用一次配置文件中的值,就要聲明一個局部變量。有沒有用代碼的方式,直接讀取配置文件中的值。

答案就是重寫PropertyPlaceholderConfigurer

public class PropertyPlaceholder extends PropertyPlaceholderConfigurer {  private static Map<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 context properties  public static Object getProperty(String name) {    return propertyMap.get(name);  }}

在配置文件中,用上面的類,代替PropertyPlaceholderConfigurer

 <bean id="propertyConfigurer" class="com.gyoung.mybatis.util.PropertyPlaceholder">    <property name="location">      <value>classpath:config.properties</value>    </property>  </bean>

這樣在代碼中就可以直接用編程方式獲取

 PropertyPlaceholder.getProperty("sql.name");

如果是多個配置文件,配置locations屬性

<bean id="propertyConfigurer"     class="com.gyoung.mybatis.util.PropertyPlaceholder">    <property name="ignoreResourceNotFound" value="true"/>    <property name="locations">      <list>        <value>file:./jdbc.properties</value>        <value>file:./module.config.properties</value>        <value>classpath:jdbc.properties</value>        <value>classpath*:*.config.properties</value>      </list>    </property>  </bean>

總結

以上就是本文關于Spring用代碼來讀取properties文件實例解析的全部內容,希望對大家有所幫助.


注:相關教程知識閱讀請移步到JAVA教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 郓城县| 马关县| 定安县| 易门县| 山东省| 吴忠市| 金坛市| 七台河市| 永顺县| 舞钢市| 霍邱县| 东丽区| 德令哈市| 张家港市| 榕江县| 景谷| 方城县| 温泉县| 酉阳| 浏阳市| 阿坝| 丰原市| 虹口区| 海宁市| 高碑店市| 遂川县| 临沂市| 广德县| 深州市| 沙河市| 高雄县| 东平县| 望奎县| 宝兴县| 乌拉特后旗| 安平县| 白朗县| 武冈市| 金阳县| 乐安县| 吉水县|