http://www.jianshu.com/p/5206f74a4406

*********************************

前言

上一篇文章介绍了SpringBoot的EnableAutoConfiguration,并通过自定义注解来实现相同的功能。
这里再介绍一下SpringBoot的配置文件的加载机制,SpringBoot会默认加载ClassPath下的application.properties的文件,下面会介绍实现的原理,并通过自定义PropertySourceLoader来自定义配置加载。

PropertySourceLoader

SpringBoot加载配置文件的入口是ConfigFileApplicationListener,这个类实现了ApplicationListenerEnvironmentPostProcessor两个接口。
SpringApplication在初始化的时候会加载spring.factories配置的ApplicationListener接口的实现类。

    private void initialize(Object[] sources) {
if (sources != null && sources.length > 0) {
this.sources.addAll(Arrays.asList(sources));
}
this.webEnvironment = deduceWebEnvironment();
setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
this.mainApplicationClass = deduceMainApplicationClass();
}

ConfigFileApplicationListener包含了PropertySourcesLoader,这个类会从spring.factories加载PropertySourceLoader的实现类。

    public PropertySourcesLoader(MutablePropertySources propertySources) {
Assert.notNull(propertySources, "PropertySources must not be null");
this.propertySources = propertySources;
this.loaders = SpringFactoriesLoader.loadFactories(PropertySourceLoader.class,getClass().getClassLoader());
}

PropertySourceLoader就是加载配置接口类。

    public interface PropertySourceLoader {
String[] getFileExtensions();
PropertySource<?> load(String name, Resource resource, String profile)
throws IOException;
}

getFileExtensions()是返回支持的文件扩展名,比如PropertiesPropertySourceLoader支持的扩展是xmlproperties
ConfigFileApplicationListener定义了默认的文件名DEFAULT_NAMES="application",所以SpringBoot会根据文件名加扩展名来加载文件。
load方法会读取配置文件,并返回PropertySource,SpringBoot会从PropertySource读取配置项,合并到总的配置对象中。

自定义PropertySourceLoader

所以自定义PropertySourceLoader就需要实现接口类,并配置到spring.factories中。
SpringBoot没有加载json的配置文件,这里就自定义JsonPropertySourceLoader来实现json格式配置文件的加载。完整的代码放在Github

  1. 定义JsonPropertySourceLoader,这里返回json的扩展名,通过SpringBoot内置的JsonParse,解析文件。
    解析成map格式,然后根据json的层级结构,递归进去,拼接成完整的key。

     public class JsonPropertySourceLoader implements PropertySourceLoader {
    public String[] getFileExtensions() {
    return new String[]{"json"};
    }
    public PropertySource<?> load(String name, Resource resource, String profile) throws IOException {
    Map<String, Object> result = mapPropertySource(resource);
    return new MapPropertySource(name, result);
    }
    private Map<String, Object> mapPropertySource(Resource resource) throws IOException {
    if (resource == null) {
    return null;
    }
    Map<String, Object> result = new HashMap<String, Object>();
    JsonParser parser = JsonParserFactory.getJsonParser();
    Map<String, Object> map = parser.parseMap(readFile(resource));
    nestMap("", result, map);
    return result;
    }
    private String readFile(Resource resource) throws IOException {
    InputStream inputStream = resource.getInputStream();
    List<Byte> byteList = new LinkedList<Byte>();
    byte[] readByte = new byte[1024];
    int length;
    while ((length = inputStream.read(readByte)) > 0) {
    for (int i = 0; i < length; i++) {
    byteList.add(readByte[i]);
    }
    }
    byte[] allBytes = new byte[byteList.size()];
    int index = 0;
    for (Byte soloByte : byteList) {
    allBytes[index] = soloByte;
    index += 1;
    }
    return new String(allBytes);
    }
    private void nestMap(String prefix, Map<String, Object> result, Map<String, Object> map) {
    if (prefix.length() > 0) {
    prefix += ".";
    }
    for (Map.Entry entrySet : map.entrySet()) {
    if (entrySet.getValue() instanceof Map) {
    nestMap(prefix + entrySet.getKey(), result, (Map<String, Object>) entrySet.getValue());
    } else {
    result.put(prefix + entrySet.getKey().toString(), entrySet.getValue());
    }
    }
    }
    }
  2. 配置文件,这里配置了customize.property.message和日志级别logging.level.root。
    {
    "customize": {
    "property": {
    "message": "hello world"
    }
    },
    "logging": {
    "level": {
    "root": "ERROR"
    }
    }
    }
  3. 配置PropertySourceLoader,在工程下新建/META-INF/spring.factories文件,并配置JsonPropertySourceLoader
    org.springframework.boot.env.PropertySourceLoader=org.wcong.test.springboot.JsonPropertySourceLoader
  4. main入口,取出customize.property.message并打印出来。
     @Configuration
    @EnableAutoConfiguration
    public class CustomizePropertySourceLoader {
    @Value("${customize.property.message}")
    private String message;
    public static void main(String[] args) {
    SpringApplication springApplication = new SpringApplication(CustomizePropertySourceLoader.class);
    springApplication.setWebEnvironment(false);
    ConfigurableApplicationContext configurableApplicationContext = springApplication.run(args);
    CustomizePropertySourceLoader customizePropertySourceLoader = configurableApplicationContext.getBean(CustomizePropertySourceLoader.class);
    System.out.println(customizePropertySourceLoader.message);
    }
    }

结语

SpringBoot通过spring.factories实现了很好的扩展功能。自定义模块相关一般是通过实现对应的接口,并配置到文件中。后面会介绍更多关于SpringBoot的内容。

文/wcong(简书作者)
原文链接:http://www.jianshu.com/p/5206f74a4406
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。
 

深入SpringBoot:自定义PropertySourceLoader的更多相关文章

  1. 深入SpringBoot:自定义Endpoint

    前言 上一篇文章介绍了SpringBoot的PropertySourceLoader,自定义了Json格式的配置文件加载.这里再介绍下EndPoint,并通过自定EndPoint来介绍实现原理. En ...

  2. SpringBoot自定义拦截器实现IP白名单功能

    SpringBoot自定义拦截器实现IP白名单功能 转载请注明源地址:http://www.cnblogs.com/funnyzpc/p/8993331.html 首先,相关功能已经上线了,且先让我先 ...

  3. SpringBoot自定义错误信息,SpringBoot适配Ajax请求

    SpringBoot自定义错误信息,SpringBoot自定义异常处理类, SpringBoot异常结果处理适配页面及Ajax请求, SpringBoot适配Ajax请求 ============== ...

  4. SpringBoot自定义错误页面,SpringBoot 404、500错误提示页面

    SpringBoot自定义错误页面,SpringBoot 404.500错误提示页面 SpringBoot 4xx.html.5xx.html错误提示页面 ====================== ...

  5. springboot自定义错误页面

    springboot自定义错误页面 1.加入配置: @Bean public EmbeddedServletContainerCustomizer containerCustomizer() { re ...

  6. SpringBoot自定义Filter

    SpringBoot自定义Filter SpringBoot自动添加了OrderedCharacterEncodingFilter和HiddenHttpMethodFilter,当然我们可以自定 义F ...

  7. springboot 自定义LocaleResolver切换语言

    springboot 自定义LocaleResolver切换语言 我们在做项目的时候,往往有很多项目需要根据用户的需要来切换不同的语言,使用国际化就可以轻松解决. 我们可以自定义springboor中 ...

  8. SpringMVC拦截器与SpringBoot自定义拦截器

    首先我们先回顾一下传统拦截器的写法: 第一步创建一个类实现HandlerInterceptor接口,重写接口的方法. 第二步在XML中进行如下配置,就可以实现自定义拦截器了 SpringBoot实现自 ...

  9. [技术博客] SPRINGBOOT自定义注解

    SPRINGBOOT自定义注解 在springboot中,有各种各样的注解,这些注解能够简化我们的配置,提高开发效率.一般来说,springboot提供的注解已经佷丰富了,但如果我们想针对某个特定情景 ...

随机推荐

  1. oracle 判断字符串是否日期格式

    select case when to_char(TO_DATE(NVL('2015- 8', 'a'), 'yyyy-mm'),'yyyy-mm')='2015- 8' then 1 else 0 ...

  2. Java学习-047-数值格式化及小数位数四舍五入

    此小工具类主要用于数值四舍五入.数值格式化输出,很简单,若想深入研究,敬请自行查阅 BigDecimal 或 DecimalFormat 的 API,BigDecimal.setScale(位数,四舍 ...

  3. Java学习-044-文件拷贝

    不用说了,又是一个经常用到的方法,直接上码了...敬请各位小主参阅!若有不足,敬请指正,非常感谢! 文件拷贝源码: /** * <strong>文件拷贝</strong>< ...

  4. ios数据库SQLite实现

    SQLite嵌入式数据库 1.支持时间,不需要配置,不需要安装,不需要管理员; 2.支持大部分SQL92; 3.完整的数据库保存在磁盘上面的一个文件,同一个数据库文件可以在不同机器上面使用.最大支持数 ...

  5. Nginx基础整理

    目录结构如下: Nginx基础知识 Nginx HTTP服务器的特色及优点 Nginx的主要企业功能 Nginx作为web服务器的主要应用场景包括: Nginx的安装 安装环境 快速安装命令集合 各个 ...

  6. linux下安装编译php的curl扩展

    curl扩展的位置(需要编译的版本)/root/install/php-5.5.24/ext/curl 1.进入对应的扩展目录 # cd /root/install/php-5.5.24/ext/cu ...

  7. 前端开发利器-Brackets IDE

    是什么? http://brackets.io/ A modern, open source text editor that understands web design. 现代, 开源的文本编辑器 ...

  8. oracle数据导出工具sqluldr2

    oracle数据导出工具sqluldr2可以将数据以csv.txt等格式导出,适用于大批量数据的导出,导出速度非常快.导出后可以使用oracle loader工具将数据导入.下载完sqluldr2,工 ...

  9. 隐藏,显示任务栏,桌面 C++代码

    HWND desktop,task; desktop=FindWindow(L"ProgMan",NULL); task=FindWindow(L"Shell_TrayW ...

  10. C++ DateTime 结构

    OS:Win7 ,Tools:VS2015 DateTime.h #pragma once struct DateTime { public: unsigned Year; // years sinc ...