問題記錄
在完成專案的程序中,遇到了這樣一個問題:讀取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 = https://www.cnblogs.com/01000001-world/p/props.getProperty(key.trim());
if(StringUtils.isBlank(value)){
return null;
}
return value.trim();
}
public static String getProperty(String key,String defaultValue){
String value = https://www.cnblogs.com/01000001-world/p/props.getProperty(key.trim());
if(StringUtils.isBlank(value)){
value = https://www.cnblogs.com/01000001-world/p/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")
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/264059.html
標籤:Java
