• 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;
        }
    
  • 相关阅读:
    相机的使用
    win11系统必知知识
    学历真的没有用吗?
    你的牙齿还好吗?
    管理
    excel导入工具类
    excel导出工具类
    StringUtil工具类
    Python 面向对象
    Python 反射
  • 原文地址:https://www.cnblogs.com/xcmelody/p/12200833.html
Copyright © 2020-2023  润新知