是否可以從.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