java – 从json文件加载spring-boot属性
发布时间:2020-12-15 04:39:17 所属栏目:Java 来源:网络整理
导读:是否可以从.json文件加载 spring-boot配置而不是.yaml或.properties?从查看文档来看,这不是开箱即用的支持 – 我想知道它是否可能,如果是这样,人们会怎么做呢? 解决方法 春季引导方式: @EnableAutoConfiguration@Configuration@PropertySource(value = {
是否可以从.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 希望有所帮助, 阿图尔 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |