/**
* 声明: 仅仅是为了测试用,知道可以这样用,一般不这样用
* <pre>
* 方式一:
* 步骤:
* 1. 自己实现EnvironmentPostProcessor接口,在spring.factories文件中配置EnvironmentPostProcessor对应类
* 该类需要添加@Order(Integer.MIN_VALUE)注解,确保该EnvironmentPostProcessor在SpringApplicationJsonEnvironmentPostProcessor之前执行
* 因为这个JSON配置最终是由SpringApplicationJsonEnvironmentPostProcessor解析的
* org.springframework.boot.env.EnvironmentPostProcessor=luck.spring.boot.post.Post
* 2. 在postProcessEnvironment读取路径下的JSON配置文件,这个实现方式仁者见仁智者见智,随便怎么实现
* 但是有要求,如下
* 因为不管如何配置,springboot取配置最终都在environment.getPropertySources()中获取配置
* 所以在PropertySource中,必须存在一个键值对; 其中key为: spring.application.json 或者 SPRING_APPLICATION_JSON
* 值为json格式的配置,json不能有空格,key必须为""包裹,这是在这种场景中JSON解析的一个规范
* 这个时候,SpringBoot就会从environment.getPropertySources()获取spring.application.json这个JSON值进行解析
* 然后解析成对应的配置类,所以这串JSON就会变成一个对象了,然后自然就可以获取到对应的配置
*
* 方式二: 添加命令行参数,key为:spring.application.json,value为配置的json,不能有空格,key需要使用""(有必要可以转义)包裹
* --spring.application.json="{\"a\":1,\"b\":2}"
* --SPRING_APPLICATION_JSON="{\"a\":3,\"b\":4}"
* 这种方式,SpringBoot会封装成命令行的参数,最终也会保存到environment.getPropertySources()中
*
*
* 以上两种方式原理: org.springframework.boot.env.SpringApplicationJsonEnvironmentPostProcessor类中,会读取该key对应的配置,加载到env对象中
*
*
* 方式三(最推荐): 创建一个指定文件后缀的属性文件加载器
* JsonPropertySourceLoader extends YamlPropertySourceLoader在spring.factories文件中配置
* org.springframework.boot.env.PropertySourceLoader= luck.spring.boot.spi.JsonPropertySourceLoader
* 因为加载配置文件之前,会将spring.factories中的PropertySourceLoader,然后找了指定配置路径下的所有配置文件
* 如果没有这个json解析器,那么json文件就不会被解析,有了之后就会将json文件也解析成配置
*
* </pre>
*/
@Order(Integer.MIN_VALUE)
public class Post implements EnvironmentPostProcessor {
@SneakyThrows
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
// 实现方式一,读取json文件,新增一个MapPropertySource保存到MutablePropertySources中
MutablePropertySources sources = environment.getPropertySources();
File file = new File(this.getClass().getClassLoader().getResource("application.json").getFile());
JSON json = JSONUtil.readJSON(file, Charset.defaultCharset());
Map<String, Object> map = Map.of("spring.application.json", json.toJSONString(0));
sources.addFirst(new MapPropertySource("spring.application.json", map));
// 实现方式二,读取json文件,不再新增PropertySource,而是在原有的PropertySource中,添加一个键值对
// 其中,key为:spring.application.json: value为json配置内容
// 获取系统属性systemProperties或者systemEnvironment都行,将这对key-value保存到系统属性中
// PropertiesPropertySource propertySource = (PropertiesPropertySource) sources.get(SYSTEM_PROPERTIES_BEAN_NAME);
// Map<String, Object> map = propertySource.getSource();
// map.put("spring.application.json", json.toJSONString(0));
}
}
public class JsonPropertySourceLoader extends YamlPropertySourceLoader {
@Override
public String[] getFileExtensions() {
return new String[]{"json"};
}
@Override
public List<PropertySource<?>> load(String name, Resource resource) throws IOException {
return super.load(name, resource);
}
}
SpringBoot2.2.2版本使用application.json作为配置文件
于 2024-04-08 16:42:14 首次发布