Java – load spring boot properties from JSON file

Is it possible to start from The JSON file loads the spring boot configuration instead of Yaml or properties? From looking at the documentation, this is not out of the box support – I wonder if it is possible, and if so, what will people do?

Solution

Spring guidance mode:

@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 through the @ propertysource annotation Read resources, set properties, and use them anywhere

The only problem is how to translate nested attributes Spring's method (by the way, you can define JSON as a variable of attribute, see: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html )Translate nested attributes as follows:

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

Change to:

test.test2.x

I hope it helps,

Artur

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>