簡體   English   中英

從json文件加載spring-boot屬性

[英]Load spring-boot properties from json file

是否可以從.json文件加載spring-boot配置而不是.yaml或.properties? 從查看文檔來看,這不是開箱即用的支持 - 我想知道它是否可能,如果是這樣,人們會怎么做呢?

春季引導方式:

@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

希望有所幫助,

阿圖爾

可以在命令行上使用環境變量提供SPRING_APPLICATION_JSON屬性。 例如,您可以在UN * X shell中使用以下行:

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

在前面的示例中,您最終在Spring環境中使用了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個步驟

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

得到了帖子

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,然后將所有找到的屬性添加到Environment

正如文檔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,以便將其包含在您需要的任何項目中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM