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