你的位置:首页 > 软件开发 > Java > 读取配置文件随想

读取配置文件随想

发布时间:2016-08-19 16:00:03
无论项目大小,数据库、开发环境、测试环境....这些信息,肯定不能在程序中硬编码。 硬编码有百坏而无一利,每次信息变动都要重新编译项目,不能分离运维和开发。 而且配置散落在项目的程序中,无法做到准确集中管理,拖慢项目进度。 我想这也是配置文件出 ...

   无论项目大小,数据库、开发环境、测试环境....这些信息,肯定不能在程序中硬编码。

   硬编码有百坏而无一利,每次信息变动都要重新编译项目,不能分离运维和开发。

   而且配置散落在项目的程序中,无法做到准确集中管理,拖慢项目进度。

   我想这也是配置文件出现的原因,配置文件比较主流的格式 properties(键值对形式)、

   本文已比较常见、简单的 properties 格式的配置文件为例,来看看读取配置文件几种不同的姿势,关注其中的实现和使用,设计模式另表。

1. SpringApache Commons Configuration

   Spring 提供了默认的配置文件读取实现类  org.springframework.core.io.DefaultResourceLoader。

   当然你也可以实现  org.springframework.core.io.ResourceLoader 接口自定义配置文件载入实现类。

   org.springframework.core.io.DefaultResourceLoader 核心方法 getResource:

public Resource getResource(String location) {    Assert.notNull(location, "Location must not be null");    Iterator ex = this.protocolResolvers.iterator();    Resource resource;    do {      if(!ex.hasNext()) {        if(location.startsWith("/")) {          return this.getResourceByPath(location);        }        if(location.startsWith("classpath:")) {          return new ClassPathResource(location.substring("classpath:".length()), this.getClassLoader());        }        try {          URL ex1 = new URL(location);          return new UrlResource(ex1);        } catch (MalformedURLException var5) {          return this.getResourceByPath(location);        }      }      ProtocolResolver protocolResolver = (ProtocolResolver)ex.next();      resource = protocolResolver.resolve(location, this);    } while(resource == null);    return resource;  }

 

海外公司注册、海外银行开户、跨境平台代入驻、VAT、EPR等知识和在线办理:https://www.xlkjsw.com

原标题:读取配置文件随想

关键词:

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

可能感兴趣文章

我的浏览记录