2017-06-15 229 views
0

是否可以從.json文件加載spring-boot配置,而不是.yaml或.properties?從查看文檔,這不支持開箱即用 - 我想知道是否有可能,如果有的話,如何去做呢?從json文件加載彈簧引導屬性

+1

你爲什麼要從json加載配置? – lihongxu

+0

這是一個圍繞彈簧引導包裝的框架。框架的用戶更喜歡使用json作爲配置文件。 –

+0

在spring引導加載yaml之前將json轉換爲yaml。 – lihongxu

回答

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; 
} 

the post

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); 
    } 
    } 
} 

the post

有這麼你可以結合兩者。裝入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