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 的方式
完成

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章