前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >springboot 自定义配置解析器

springboot 自定义配置解析器

作者头像
分享干货的你
发布2021-04-06 16:18:50
1.1K0
发布2021-04-06 16:18:50
举报
文章被收录于专栏:分享干货的你分享干货的你

假如有一个需求: 初始化要加载很多的JSON 格式的文件, 到Spring容器中,spring 上下文。 直接使用@value 注解获取一些属性值。 这种就需要自己来自定义解析器, springboot 默认支持application.properties 和 application.yml ,这里我们要自定义application.json , 解析json 文件, 变成kv的map 形式。 再用@value 注解获取。

我们看一下propertySourceLoad 的源码

第一个方法返回的是后缀是什么格式的。

第二个是加载文件变成 PropertySource 。

第三个是要返回MapPropertySource 变成k,v 形式 才能被 @Value 识别。

第四最后在加入META-INF/spring.factories里面,

org.springframework.boot.env.PropertySourceLoader =xxxx

指定自定义的ProPertySourceLoader

代码

代码语言:javascript
复制
/**
 *  自定义json 配置文件解析器 ,可以使用@Value 的注解
 */
public class JsonPropertySourceLoader implements PropertySourceLoader {

    /**
     *  返回支持的文件扩展名, 目前只支持json
     * @return
     */
    @Override
    public String[] getFileExtensions() {
        return new String[]{"json"};
    }

    /**
     *  把json 转成key value 形式
     * @param name
     * @param resource
     * @return
     * @throws IOException
     */
    @Override
    public List<PropertySource<?>> load(String name, Resource resource) throws IOException {
        return Collections.singletonList(new MapPropertySource(name, mapPropertySource(resource)));
    }

    /**
     * Resource转Map
     *
     * @param resource
     * @return
     */
    private Map<String, Object> mapPropertySource(Resource resource) {

        Map<String, Object> result = new HashMap<>();
        // 获取json格式的Map
        Map<String, Object> fileMap = JSONObject.parseObject(readFile(resource),Map.class);
        // 组装嵌套json
        processorMap("", result, fileMap);
        return result;
    }

    private void processorMap(String prefix, Map<String, Object> result, Map<String, Object> fileMap) {
        if (prefix.length() > 0) {
            prefix += ".";
        }
        for (Map.Entry<String, Object> entrySet : fileMap.entrySet()) {
            if (entrySet.getValue() instanceof Map) {
                processorMap(prefix + entrySet.getKey(), result, (Map<String, Object>) entrySet.getValue());
            } else {
                result.put(prefix + entrySet.getKey(), entrySet.getValue());
            }
        }
    }

    /**
     * JSON格式
     *
     * @param resource
     * @return
     */
    private String readFile(Resource resource) {
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(resource.getFile());
            String str = "";
            byte[] readByte = new byte[1024];
            int length;
            while ((length = fileInputStream.read(readByte)) > 0) {
                str += new String(readByte, 0, length, "UTF-8");
            }

            return str;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2021-03-22,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 分享干货的你 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档