Spring Boot自定义PropertySourceLoader

转载自:
http://blog.csdn.net/catoop/article/details/71157986
http://blog.csdn.net/liaokailin/article/details/48194777
http://www.jianshu.com/p/5206f74a4406

  SpringBoot加载配置文件的入口是ConfigFileApplicationListener,这个类实现了ApplicationListenerEnvironmentPostProcessor两个接口。在SpringApplication在初始化的时候会加载spring.factories配置的ApplicationListener接口的实现类。源码分析参看:http://blog.csdn.net/liaokailin/article/details/48878447

  ConfigFileApplicationListener中有个内部类Loader,该类中包含了PropertySourcesLoader,这个类的构造函数中会从spring.factories加载PropertySourceLoader的实现类。调用链是

SpringApplication.prepareEnvironment
---> listeners.environmentPrepared(environment) ---> ConfigFileApplicationListener.onApplicationEnvironmentPreparedEvent ---> ConfigFileApplicationListener.postProcessEnvironment ---> ConfigFileApplicationListener.addPropertySources ---> new Loader(environment, resourceLoader).load();

  spring.factories中配置的PropertySourcesLoaderPropertiesPropertySourceLoaderYamlPropertySourceLoader分别对应properties和xml的Loader、yml和yaml对应的Loader。这2个类都实现自接口PropertySourceLoader。

  如果需要自定义其它格式的Loader就需要实现接口类PropertySourceLoader,并配置到spring.factories中。现在想扩展采用HOCON格式的配置类,如下:

package org.zero;

import com.typesafe.config.Config;
import com.typesafe.config.ConfigException;
import com.typesafe.config.ConfigFactory;
import org.springframework.boot.env.PropertySourceLoader;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;

import java.io.IOException;

public class HOCONPropertySourceLoader implements PropertySourceLoader {

    // 配置文件格式(扩展名)
    @Override
    public String[] getFileExtensions() {
        return new String[]{"conf"};
    }

    @Override
    public PropertySource<?> load(String name, Resource resource, String profile) throws IOException {
        if (profile == null) {
            try {
                Config config = ConfigFactory.parseFile(resource.getFile());
                return new HOCONPropertySource(name, config);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static class HOCONPropertySource extends PropertySource<Config> {
        public HOCONPropertySource(String name, Config config) {
            super(name, config);
        }

        @Override
        public Object getProperty(String name) {
            try {
               return getSource().getString(name);
            }catch (ConfigException e){
                return null;
            }
        }
    }
}

  然后在src/main/resources中创建 META-INF/spring.factories文件,内容为:

org.springframework.boot.env.PropertySourceLoader=\
org.zero.HOCONPropertySourceLoader

  这样在项目中就可以使用HOCON格式的配置文件了。

    原文作者:Spring Boot
    原文地址: https://blog.csdn.net/zero__007/article/details/78321564
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞