资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

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

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

创新互联建站专注于兴平网站建设服务及定制,我们拥有丰富的企业做网站经验。 热诚为您提供兴平营销型网站建设,兴平网站制作、兴平网页设计、兴平网站官网定制、重庆小程序开发公司服务,打造兴平网络公司原创品牌,更为您提供兴平网站排名全网营销落地服务。

一、通过Spring工厂读取

示例:

public class PropertyConfig {
	private static AbstractBeanFactory beanFactory = null;
	private static final Map 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的配置


  
  
  
    
      classpath:props/${property-path}.properties
      classpath:important.properties
    
  

在项目中使用

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配置文件示例代码的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!


文章标题:使用spring工厂读取property配置文件示例代码
文章出自:http://cdkjz.cn/article/psosic.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220