1. 程式人生 > >FileSystemResource在Srping FrameWork 5中的變化

FileSystemResource在Srping FrameWork 5中的變化

nio gen location try cte res exce file debug

之前在項目中一直使用FileSystemResource這個類作為PropertyPlaceholderConfigurer的Resource引入部署目錄外的配置文件,並設置了setIgnoreResourceNotFound為true,最近把Spring Framework升級為5.0.2,當外部配置文件不存在時,PropertyPlaceholderConfigurer的初始化會報錯,貌似setIgnoreResourceNotFound不再起作用,今天看了一下源碼

先看PropertyPlaceholderConfigurer的父類PlaceholderConfigurerSupport中的一段:

/**
* Load properties into the given instance.
* @param props the Properties instance to load into
* @throws IOException in case of I/O errors
* @see #setLocations
*/
protected void loadProperties(Properties props) throws IOException {
    if (this.locations != null) {
        for (Resource location : this.locations) {
            if (logger.isDebugEnabled()) {
                logger.debug("Loading properties file from " + location);
            }
            try {
                PropertiesLoaderUtils.fillProperties(
                        props, new EncodedResource(location, this.fileEncoding), this.propertiesPersister);
            }
            catch (IOException ex) {
                // Resource not found when trying to open it
                if (this.ignoreResourceNotFound &&
                        (ex instanceof FileNotFoundException || ex instanceof UnknownHostException)) {
                    if (logger.isInfoEnabled()) {
                        logger.info("Properties resource not found: " + ex.getMessage());
                    }
                }
                else {
                    throw ex;
                }
            }
        }
    }
}

得知,在設置了ignoreResourceNotFound之後,Resource類拋出的異常必須是FileNotFoundException才能生效,但是在Spring Framework 5中FileSystemResource已經換用nio下面的包來實現了,拋出的也是nio包下面的異常java.nio.file.NoSuchFileException,所以ignoreResourceNotFound不再有效,從FileSystemResource的說明中得知還有PathResource這個類,就換它試了一下,問題解決。

FileSystemResource在Srping FrameWork 5中的變化