問題記錄
在完成項目的過程中,遇到了這樣一個問題:讀取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")