在上一篇文章, 我们使用了propertiesSourceLoad 实现了,加载JSON 文件 , 在使用@value 注解获取json 格式配置文件的值。 但是存在两个问题,json 的名字不能自己定义,只能叫application.json . 并且好像打成jar包的时候,classPathResource 好像获取不到这个json 文件。
应为他是一个jar包,不是文件,获取路径前面会加上一个!号的。
这里需要用this.getclass.getclassload.getResourceAsStream()
获取路径。
这里我们使用 propertiesSourceLoad 的上一级, customJsonEnvironmentPostProcessor 来 实现。
1, 首先看一下 EnvironmentPostProcessor 这个类,
其中systemEnvironmentPropertySourceEnvironmentPostProcessor
就是加载系统环境属性的
2,我们类比仿写一个,自己实现EnvironmentPostProcessor
public class CustomJsonEnvironmentPostProcessor implements EnvironmentPostProcessor {
/**
* 后缀名
*/
private static final String FILE_PATH = "xxxxxx.json";
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
environment.getPropertySources().addLast(new MapPropertySource(FILE_PATH, mapPropertySource()));
}
/**
* Resource转Map
* @return
*/
private Map<String, Object> mapPropertySource() {
Map<String, Object> result = new HashMap<>();
// 获取json格式的Map
Map<String, Object> fileMap = JSONObject.parseObject(readFile(),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格式
* @return
*/
private String readFile() {
InputStream fileInputStream = null;
try {
// 具体改动的地方
fileInputStream = this.getClass().getClassLoader().getResourceAsStream(FILE_PATH);
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;
}
}
2, 同理在spring.factories 里面
在把自己的类加上面。