使用spring工厂读取property配置文件示例代码

发布时间:2020-09-25 16:19:52 作者:yanweiqi
来源:脚本之家 阅读:119

本文将介绍两种Spring读取property配置文件的方法,接下来看看具体内容。

一、通过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;
	}
	/**   
   * 根据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");

总结

以上就是本文关于使用spring工厂读取property配置文件示例代码的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

推荐阅读:
  1. spring-boot读取props和yml配置文件
  2. Spring怎么读取配置文件属性

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

spring 读取配置文件

上一篇:java实现合并单元格的同时并导出excel示例

下一篇:Node.js中package.json中库的版本号(~和^)

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》