Load spring-boot properties from json file

时间:2017-06-15 09:42:10

标签: java json spring spring-boot properties

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'm wondering if it's possible and if so how one would go about doing it?

4 个答案:

答案 0 :(得分:4)

The spring boot way:

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

    }
}

Define your own PropertySourceFactory and hook it in via the @PropertySource annotation. Read the resource, set the properties, use them anywhere.

Only thing is, how do you translate nested properties. The Spring way to do that (by the way you can define Json also as a variable for properties, see: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html) is to translate nested properties as such:

{"test": { "test2" : "x" } }

Becomes:

test.test2.x

Hope that helps,

Artur

答案 1 :(得分:2)

SPRING_APPLICATION_JSON属性可以在命令行中提供环境变量。例如,您可以在UN * X shell中使用以下行:

  

$ SPRING_APPLICATION_JSON ='{“ acme”:{“ name”:“ test”}}''java -jar   myapp.jar

在前面的示例中,您最终在Spring Environment中获得了acme.name = test。您还可以在System属性中将JSON作为spring.application.json提供,如以下示例所示:

  

$ java -Dspring.application.json ='{“ name”:“ test”}'-jar myapp.jar

您还可以使用命令行参数来提供JSON,如以下示例所示:

  

$ java -jar myapp.jar --spring.application.json ='{“ name”:“ test”}'

您还可以将JSON作为JNDI变量提供,如下所示:

  

java:comp / env / spring.application.json。

参考文档:https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

答案 2 :(得分:1)

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

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

答案 3 :(得分:1)

in docson GitHub

所示
  

YAML是JSON的超集

因此,您只需在Spring Boot项目中创建以下类:

public class JsonPropertySourceLoader extends YamlPropertySourceLoader {
    @Override
    public String[] getFileExtensions() {
        return new String[]{"json"};
    }
}

然后创建一个文件:

/src/main/resources/META-INF/spring.factories 具有以下内容:

org.springframework.boot.env.PropertySourceLoader=\
io.myapp.JsonPropertySourceLoader

您的Spring应用程序已准备好从application.json加载JSON配置。优先级将为:.properties-> .yaml-> .json

如果您有多个应用程序,则可以使用共享的PropertySourceLoaderspring.factories文件创建一个jar,以便将其包含在所需的任何项目中。