2017-06-15 231 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