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

首頁 > 開發(fā) > Java > 正文

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

2024-07-13 10:16:16
字體:
供稿:網(wǎng)友

本文將介紹兩種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>

在項(xiàng)目中使用

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

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

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)專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!


注:相關(guān)教程知識(shí)閱讀請移步到JAVA教程頻道。
發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 收藏| 晋中市| 周口市| 左贡县| 巴中市| 社会| 马鞍山市| 深圳市| 盐亭县| 德阳市| 宁远县| 井冈山市| 奉新县| 集安市| 龙门县| 五河县| 南涧| 确山县| 徐水县| 菏泽市| 乌鲁木齐县| 曲靖市| 徐闻县| 琼中| 阿拉善左旗| 安化县| 炉霍县| 和政县| 元江| 当雄县| 都匀市| 定兴县| 吴旗县| 贞丰县| 城固县| 泗水县| 和硕县| 开平市| 裕民县| 武川县| 高碑店市|