Load spring-boot properties from json file

前端 未结 4 1035
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-31 23:57

Is it possible to load spring-boot config from a .json file as opposed to .yaml or .properties? From looking at the documentation, this isn\'t supported out of the box - I\'

4条回答
  •  庸人自扰
    2021-01-01 00:44

    2 steps

    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 from the post

    and

    public class YamlFileApplicationContextInitializer implements ApplicationContextInitializer {
      @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);
        }
      }
    }
    

    Got from the post

    So you can combine both. Load your json as resource and convert to yaml and then add to Environment all the found properties

提交回复
热议问题