Spring 通配符加载Resource文件

Posted 热咖啡与白猫

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring 通配符加载Resource文件相关的知识,希望对你有一定的参考价值。

Spring 通配符加载Resource文件

SpringResource继承自InputStreamSource

其中InputStreamSource接口定义了获取java.io.InputStream流的规范

InputStreamSource

public interface InputStreamSource {
    /**
     * 返回{@link InputStream}
     * 每次调用都创建新的steram
     * @return the input stream for the underlying resource (必须不为{@code null})
     * @throws java.io.FileNotFoundException 如果resource不存在抛出异常
     * @throws IOException 如果无法打开抛出IO异常
     */
    InputStream getInputStream() throws IOException;
}

对于Resource定义了操作资源文件的一些基本规范

public interface Resource extends InputStreamSource {
    boolean exists();
    default boolean isReadable() {
        return exists();
    }
    default boolean isOpen() {
        return false;
    }
    default boolean isFile() {
        return false;
    }
    URL getURL() throws IOException;
    URI getURI() throws IOException;
    File getFile() throws IOException;
    default ReadableByteChannel readableChannel() throws IOException {
        return Channels.newChannel(getInputStream());
    }
    long contentLength() throws IOException;
    long lastModified() throws IOException;
    Resource createRelative(String relativePath) throws IOException;
    @Nullable
    String getFilename();
    String getDescription();
}

Spring中加载资源文件主要是ResourceLoader接口,里面定义了获取资源以及类加载器的规范
ResourceLoader

public interface ResourceLoader {
    /** Pseudo URL prefix for loading from the class path: "classpath:". */
    String CLASSPATH_URL_PREFIX = ResourceUtils.CLASSPATH_URL_PREFIX;

    Resource getResource(String location);

    ClassLoader getClassLoader();
}

Spring中的所有资源加载都是在该接口的基础上实现的

对于通配符加载多个Resource文件的主要是
ResourcePatternResolver

public interface ResourcePatternResolver extends ResourceLoader {
    String CLASSPATH_ALL_URL_PREFIX = "classpath*:";

    Resource[] getResources(String locationPattern) throws IOException;
}

通过getResources()方法即可匹配多个

比较常用的实现类为PathMatchingResourcePatternResolver

以下为配置mybatisSqlSessionFactoryBean时,设置MapperLocations的使用

    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) throws IOException {
        final SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        final PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver();
        sqlSessionFactoryBean.setMapperLocations(pathMatchingResourcePatternResolver.getResources("classpath:mapper/*.xml"));
        return sqlSessionFactoryBean;
    }

以上是关于Spring 通配符加载Resource文件的主要内容,如果未能解决你的问题,请参考以下文章

spring3: 4.4 使用路径通配符加载Resource

资源 之 4.4 Resource通配符路径(拾贰)

Spring加载resource时classpath*:与classpath:的区别

Spring加载resource时classpath*:与classpath:的区别

J2EE加载资源文件以及Spring加载XML文件

spring循环依赖问题深究