从json文件加载spring-boot属性 [英] Load spring-boot properties from json file
问题描述
是否可以从.json文件加载spring-boot配置而不是.yaml或.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?
推荐答案
春季引导方式:
@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
注释将其挂钩。阅读资源,设置属性,在任何地方使用它们。
Define your own PropertySourceFactory
and hook it in via the @PropertySource
annotation. Read the resource, set the properties, use them anywhere.
唯一的问题是,如何翻译嵌套属性。 Spring的方法(顺便说一下,您可以将Json定义为属性的变量,请参阅: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html )
用于翻译嵌套属性:
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" } }
成为:
test.test2.x
希望有所帮助,
Artur
这篇关于从json文件加载spring-boot属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!