springboot加载复杂的yml文件获取不到值的解决方案
目录
- springboot加载yml文件获不到值
- 获取不到yml配置文件指定的值
springboot加载yml文件获不到值
今天使用spring boot读取yml文件,这种多层嵌套的竟然无法读取到(value注解spring.redis.pool.max.wait),即便加上全名也不行,然后网上搜到的内容也未曾满意,很多文章内容都是一样且重复的.最后放弃了查找,突发奇想之下解决了这个问题.
本文旨在如何读取多层嵌套的yml文件,希望能帮到众位.
以下是代码:
package com.boot.config; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; @Configuration @ConfigurationProperties(prefix = "spring.redis;pool.max;pool.min") @PropertySource(value = "classpath:redis.yml") public class RedisConfiguration implements ApplicationListener<ApplicationEvent> { @Value("${host}") private String host; @Value("${port}") private Long port; @Value("${timeout}") private Long timeout; @Value("${database}") private Long database; @Value("${wait}") private Long poolMaxWait; @Value("${idle}") private Long poolMaxIdle; @Value("${idle}") private Long poolMinIdle; @Value("${active}") private Long poolMaxActive; public void onApplicationEvent(ApplicationEvent event) { // 打印属性 System.out.println("============= redisConnect ================"); System.out.println(this.toString()); } @Override public String toString() { return "RedisConfiguration [host=" + host + ", port=" + port + ", timeout=" + timeout + ", database=" + database + ", poolMaxWait=" + poolMaxWait + ", poolMaxIdle=" + poolMaxIdle + ", poolMinIdle=" + poolMinIdle + ", poolMaxActive=" + poolMaxActive + "]"; } }
#多层配置 spring: redis: database: 0 host: localhost port: 6379 timeout: 0 pool: max: active: 8 wait: -1 idle: 8 min: idle: 0
日志打印如下所示:
============= redisConnect ================
RedisConfiguration [host=localhost, port=6379, timeout=0, database=0, poolMaxWait=-1, poolMaxIdle=0, poolMinIdle=0, poolMaxActive=8]
获取不到yml配置文件指定的值
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class App { public static void main(String[] args) { SpringApplication app = new SpringApplication(App.class); ConfigurableApplicationContext context = app.run(args); System.out.println(context.getEnvironment().getProperty("jdbc.pwd")); context.close(); } }
apllication.yml 放置在classpath路径下
jdbc: pwd: 123456 #冒号和数字之间有一个空格,没有否则获取失败,pwd前面有缩进两个字符
ps:版本spring-4.3.2-release,springboot-1.4
以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。
赞 (0)