溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

使用spring工廠讀取property配置文件示例代碼

發(fā)布時間:2020-09-25 16:19:52 來源:腳本之家 閱讀:123 作者:yanweiqi 欄目:編程語言

本文將介紹兩種Spring讀取property配置文件的方法,接下來看看具體內(nèi)容。

一、通過Spring工廠讀取

示例:

public class PropertyConfig {
	private static AbstractBeanFactory beanFactory = null;
	private static final Map<String,String> cache = new oncurrentHashMap<>();
	@Inject  
	  public PropertyConfig(AbstractBeanFactory beanFactory) {
		this.beanFactory = beanFactory;
	}
	/**   
   * 根據(jù)key獲取配置文件的Value  
   * @param key   * @return   
   */
	public static String getProperty(String key) {
		String propValue = "";
		if(cache.containsKey(key)){
			propValue = cache.get(key);
		} else {
			try {
				propValue = beanFactory.resolveEmbeddedValue("${" + key.trim() + "}");
				cache.put(key,propValue);
			}
			catch (IllegalArgumentException ex) {
				ex.printStackTrace();
			}
		}
		return propValue;
	}
}

Spring xml的配置

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE"/>
  <property name="ignoreResourceNotFound" value="true"/>
  <property name="locations">
    <list>
      <value>classpath:props/${property-path}.properties</value>
      <value>classpath:important.properties</value>
    </list>
  </property>
</bean>

在項目中使用

String maxTimeInSecondsProp = PropertyConfig.getProperty("maxTimeInSeconds");

二、直接使用spirng程序代碼讀取項目的配置文件方法

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.core.io.FileSystemResource;
 
public class Test {
  /**
   * @param args
   */
  public static void main( String[] args ) {
    String configFile = "D:/test/application.properties";
    //如果配置文件在classpath目錄下可以使用ClassPathResource對象
    //Resource resource = new ClassPathResource("/application.properties");
    Resource resource = new FileSystemResource( configFile );
    try {
      Properties property = PropertiesLoaderUtils.loadProperties(resource);
      String driver = property.getProperty("jdbc.driver");
      String url = property.getProperty("jdbc.url");
      String userName = property.getProperty("jdbc.username");
      String password = property.getProperty("jdbc.password");
    }
    catch (IOException e1) {
      //log.error("read config file failed", e1);
    }
  }
}

如果配置文件在classpath目錄下可以使用ClassPathResource對象

Resource resource = new ClassPathResource("/application.properties");

總結(jié)

以上就是本文關(guān)于使用spring工廠讀取property配置文件示例代碼的全部內(nèi)容,希望對大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關(guān)專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI