首先要寫一個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 的方式
完成