java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > springboot加载json配置

springboot加载json配置全过程

作者:一只猪啊啊

Spring Boot加载JSON配置的步骤:实现PropertySourceLoader接口,创建spring.factories文件,并在resources下添加application.json,通过指定spring.profiles.active属性来激活配置文件

springboot加载json配置

首先要写一个PropertySourceLoader 的实现

public class JSONPropertySourceLoader implements PropertySourceLoader {
    @Override
    public String[] getFileExtensions() {
        return new String[]{"json"};
    }

    @Override
    public List<PropertySource<?>> load(String name, Resource resource) throws IOException {
        InputStream inputStream = resource.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        Map json = new HashMap();
        String line = null;
        while((line = br.readLine()) != null){
            JSONObject inner = JSONObject.parseObject(line);
            json.putAll(inner);
        }
        br.close();
        return Collections
                .singletonList(new OriginTrackedMapPropertySource(name, json));
    }
}

然后在resources下创建META-INF文件夹并创建 spring.factories文件

内容为

org.springframework.boot.env.PropertySourceLoader = com.cyd.project.JSONPropertySourceLoader

这样就已经实现了加载json配置的功能

创建一个 application.json文件

{"aaa":"333"}
{"xxx":2}

启动工程

我这里使用的是application.properties指定

spring.profiles.active = dev 的方式

完成~~~~

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文