起因:Findbugs “Method May Fail to Close Stream”
Insight: Properties.load(java.io.InputStream inStream)
注释声明:The specified stream remains open after this method returns.
建议的做法:
/**
* 参考Spring 对properties的处理方式
* PropertiesLoaderUtils.fillProperties() or PropertiesLoaderUtils.loadProperties()
*
* Fill the given properties from the given resource (in ISO-8859-1 encoding).
* @param new ClassPathResource(path) 封装的Resource,提供advance getInputStream()以及getFilename、exists 等方法
*/
public static void fillProperties(Properties props, Resource resource) throws IOException {
// opens an InputStream for the given class path resource
InputStream is = resource.getInputStream();
try {
String filename = resource.getFilename();
if (filename != null && filename.endsWith(XML_FILE_EXTENSION)) {
props.loadFromXML(is);
}
else {
props.load(is);
}
}
finally {
is.close(); // :)
}
}
扩展tips:
1、spring 如何加载properties
2、初始化过程中其余的utils
// main spring context 初始化过程
org.springframework.web.servlet.FrameworkServlet.initServletBean(...)
org.springframework.web.servlet.FrameworkServlet.initWebApplicionContext(...)
org.springframework.context.support.AbstractApplicionContext.refresh(...)
// ...
/**
* 基于spring.xml properties配置
*
*
**/
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(...)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreeBean(...)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(...)
// 解析location并赋值 this.locations
org.springframework.core.io.support.PropertiesLoaderSupport.setLocions(...)
// CollectionUtils.mergePropertiesIntoMap() :)
org.springframework.core.io.support.PropertiesLoaderSupport.mergeProperties(...)
// 委托PropertiesLoaderUtils.fillProperties实现properties 解析
org.springframework.core.io.support.PropertiesLoaderSupport.loadProperties(...)