读取配置文件

1. Spring 和 Apache Commons Configuration

   若是项目中没什么特殊的个性化读取配置文件需求,能够使用 Spring 管理配置文件信息,而后注入到须要的地方。java

   配置文件中须要添加(PS :多配置文件,添加 ignore-unresolvable 参数)。web

    <context:property-placeholder location="classpath:db-info.properties" ignore-unresolvable="true"/>

    <context:property-placeholder location="classpath:web.properties" ignore-unresolvable="true"/>

   而后再须要的地方spring

   动态读入能够使用 Spring 提供了默认的配置文件读取实现类  org.springframework.core.io.DefaultResourceLoader。apache

   固然你也能够实现  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;
    }

复制代码

   能够看出 Spring 能支持入参路径的不少方式,包括已 " /"、"classpath" 开头。 app

   若是你想在项目中使用 Spring 提供的默认配置文件载入实现,能够这样书写你的代码。框架

            ResourceLoader resourceLoader = = resourceLoader.getResource("log4j.properties"=

   固然你也能够引入 Apache Commons Configuration jar 内部设计至关考究。ide

   整个 jar 不超过 400K,若是时间充裕,你也能够反编译看看源码。工具

   使用方式也特别简洁,两行代码就 OK:

  PropertiesConfiguration configuration  = new PropertiesConfiguration("log4j.properties");
  configuration.getString("log4j.appender.file");

   Apache Commons Configuration 默认载入配置文件核心实现类 org.apache.commons.configuration.AbstractFileConfiguration 载入方法:

复制代码

    public void load(String fileName) throws ConfigurationException {        try {
            URL e = ConfigurationUtils.locate(this.fileSystem, this.basePath, fileName);            if(e == null) {                throw new ConfigurationException("Cannot locate configuration source " + fileName);
            } else {                this.load(e);
            }
        } catch (ConfigurationException var3) {            throw var3;
        } catch (Exception var4) {            throw new ConfigurationException("Unable to load the configuration file " + fileName, var4);
        }
    }

复制代码

回到顶部

2. JDK 经典手写

   若是你项目对读取配置文件没有太多个性化的需求,若是你有足够时间,若是你嫌弃第三方 Jar 占据你 lib 目录的一席之地,还有若是你热爱编程。

   仔细一点,你会发现,这些开源框架底层都是已 java.net.URL 载入配置文件。

   在载入配置文件的过程当中应项目需求采用了恰当的设计模式,使可以支持一些对配置文件的特定操做。

   载入文件后,实例化为 java.util.Properties 对象,进行配置文件获取。

   那就彻底能够撸段纯 JDK 的写法,做为工具类放入项目中,编译后不超过 5K,核心的几句代码以下:

          URL resource = Thread.currentThread().getContextClassLoader().getResource("log4j.properties");
          Properties properties = new Properties();
          properties.load(resource.openStream());          properties.getProperty(key);

  由于  java.util.Properties 的 load 进行了方法的重载,你也能够不用 URL 方式读取配置文件,也能够这样写:

          String url = XXXXX.class.getResource("").getPath().replaceAll("%20", " ");
          String path = url.substring(0, url.indexOf("classes")) + filePath; //该 path 为你配置文件的路径

          InputStream inputStream = new FileInputStream(path);
          BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
          prop.load(bufferedReader);prop.getProperty(key);

 上述代码都为实例核心的几句代码,其中的判空和异常都没有进行处理,仅做为参考。

 最后贴上本身封装的配置文件载入类,不使用任何第三方 jar,有须要的拿走放入项目便可用。

 View Code

  使用方式也很简单,支持多路径读入,若是存在相同 Key 后面的覆盖前面的:

        PropertiesLoader propertiesLoader = new PropertiesLoader("log4j.properties");
        System.out.println(propertiesLoader.getProperty("log4j.appender.file"));
相关文章
相关标签/搜索