是否可以从.json文件加载spring-boot配置,而不是.yaml或.properties?从查看文档,这不支持开箱即用 - 我想知道是否有可能,如果有的话,如何去做呢?从json文件加载弹簧引导属性
0
A
回答
0
2个步骤
public String asYaml(String jsonString) throws JsonProcessingException, IOException {
// parse JSON
JsonNode jsonNodeTree = new ObjectMapper().readTree(jsonString);
// save it as YAML
String jsonAsYaml = new YAMLMapper().writeValueAsString(jsonNodeTree);
return jsonAsYaml;
}
GOT和
public class YamlFileApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
try {
Resource resource = applicationContext.getResource("classpath:file.yml");
YamlPropertySourceLoader sourceLoader = new YamlPropertySourceLoader();
PropertySource<?> yamlTestProperties = yamlTestProperties = sourceLoader.load("yamlTestProperties", resource, null);
applicationContext.getEnvironment().getPropertySources().addFirst(yamlTestProperties);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
有这么你可以结合两者。装入JSON作为资源,并转换为YAML,然后添加到环境中的所有发现的属性
1
弹簧启动方式:
@EnableAutoConfiguration
@Configuration
@PropertySource(value = { "classpath:/properties/config.default.json" }, factory=SpringBootTest.JsonLoader.class)
public class SpringBootTest extends SpringBootServletInitializer {
@Bean
public Object test(Environment e) {
System.out.println(e.getProperty("test"));
return new Object();
}
public static void main(String[] args) {
SpringApplication.run(SpringBootTest.class);
}
public static class JsonLoader implements PropertySourceFactory {
@Override
public org.springframework.core.env.PropertySource<?> createPropertySource(String name,
EncodedResource resource) throws IOException {
Map readValue = new ObjectMapper().readValue(resource.getInputStream(), Map.class);
return new MapPropertySource("json-source", readValue);
}
}
}
定义自己的PropertySourceFactory
并通过@PropertySource
注释勾进去。阅读资源,设置属性,在任何地方使用它们。
唯一的是,你如何翻译嵌套属性。 Spring的方式做到这一点(顺便说一下,你可以定义的Json也作为属性变量,请参见:https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html) 是嵌套的属性,例如翻译:
{"test": { "test2" : "x" } }
变为:
test.test2.x
希望有帮助,
Artur
相关问题
- 1. 从弹簧加载多个外部属性文件
- 2. 基于弹簧配置文件的弹簧引导应用程序属性
- 3. 记录弹簧(引导)配置属性
- 4. 使用弹簧加载弹簧引导和Maven
- 5. 从命令行加载弹簧上下文属性
- 6. 弹簧引导向环境中添加另一个属性文件
- 7. 弹簧属性文件 - 附加属性true/false
- 8. 弹簧引导文件夹结构
- 9. 弹簧多个属性文件
- 10. 弹簧自动创建属性文件
- 11. 从S3加载弹簧application.profiles
- 12. 使用弹簧引导管理的非弹簧引导工程
- 13. 无法从弹簧引导罐中读取文本文件
- 14. 未设置弹簧引导配置属性
- 15. 将弹簧引导部署到elasticbeanstalk并设置系统属性
- 16. 从多个弹簧引导YAML文件合并列表
- 17. 添加一个文件到弹簧属性
- 18. 属性文件重新加载服务器上的变化,弹簧
- 19. 在弹簧数据中加载持久性配置文件jpa
- 20. 登录弹簧引导
- 21. 弹簧引导云配置
- 22. 为弹簧引导应用
- 23. 无法与弹簧引导
- 24. 从Java代码填充弹簧“属性”
- 25. 如何将日志记录属性添加到弹簧引导应用程序
- 26. 引用弹簧属性文件使用路径相对于配置文件
- 27. 将.yml文件中的所有弹簧引导属性设置为系统属性
- 28. 如何在启动时拦截弹簧引导Bean加载?
- 29. 弹簧引导@TestPropertySource不加载使用@SpringBootTest
- 30. 运行弹簧引导罐时找不到或加载主类
你为什么要从json加载配置? – lihongxu
这是一个围绕弹簧引导包装的框架。框架的用户更喜欢使用json作为配置文件。 –
在spring引导加载yaml之前将json转换为yaml。 – lihongxu