关于application.yml配置读取


问题记录

在完成项目的过程中,遇到了这样一个问题:读取application.yml信息时,报空指针异常。

application.yml配置如下:

#Cacheable 注解默认生存时间(秒)
cacheable:
redis:
ttl: 3600

在自定义的 PropertiesUtil类中,进行了对resources下 application.yml配置文件的加载

@Slf4j
public class PropertiesUtil {

private static Properties props;

static {
// String fileName = "application.properties";
String fileName = "application.yml";
props = new Properties();
try {
props.load(new InputStreamReader(PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName),"UTF-8"));
} catch (IOException e) {
log.error("配置文件读取异常",e);
}
}

public static String getProperty(String key){
String value = props.getProperty(key.trim());
if(StringUtils.isBlank(value)){
return null;
}
return value.trim();
}

public static String getProperty(String key,String defaultValue){

String value = props.getProperty(key.trim());
if(StringUtils.isBlank(value)){
value = defaultValue;
}
return value.trim();
}


}

但是当我在使用 PropertiesUtil.getProperty("cacheable.redis.ttl") 时,报错空指针异常,这让我有点摸不着头脑,就进行debug。

发现,在对 cacheable.redis.ttl 读取中key为 ttl

 

因为key值不为 cacheable.redis.ttl ,所以肯定会报空指针异常。

因此我们在yml文件中读取配置信息时,需设置为

cacheable.redis.ttl: 3600

读取的时候才为:

或者对调用方法的key值进行修改:

PropertiesUtil.getProperty("ttl") 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM