02、Resource接口与资源加载



一、资源抽象接口Resource

  Spring使用Resource装载各种资源,包括配置文件资源、国际化属性文件资源等。Resource接口位于org.springframework.core.io包下,继承interface Resource extends InputStreamSource,主要方法包含:

	/**
	 * Determine whether this resource actually exists in physical form.
	 * <p>This method performs a definitive existence check, whereas the
	 * existence of a {@code Resource} handle only guarantees a valid
	 * descriptor handle.
	 */
	boolean exists();
	
	/**
	 * Indicate whether this resource represents a handle with an open stream.
	 * If {@code true}, the InputStream cannot be read multiple times,
	 * and must be read and closed to avoid resource leaks.
	 * <p>Will be {@code false} for typical resource descriptors.
	 */
	default boolean isOpen() {
		return false;
	}
	
	/**
	 * Return a URL handle for this resource.
	 * @throws IOException if the resource cannot be resolved as URL,
	 * i.e. if the resource is not available as descriptor
	 */
	URL getURL() throws IOException;

	/**
	 * Return a File handle for this resource.
	 * @throws java.io.FileNotFoundException if the resource cannot be resolved as
	 * absolute file path, i.e. if the resource is not available in a file system
	 * @throws IOException in case of general resolution/reading failures
	 * @see #getInputStream()
	 */
	File getFile() throws IOException;

  Resource的具体实现类:
在这里插入图片描述在这里插入图片描述

二、资源加载

  1. 资源地址表达式
  • Spring支持资源类型前缀:
    在这里插入图片描述
    classpath:还可以成classpath*:,表示从多个模块中加载。例如:classpath*:com/demo/module*.xml表示加载com/demo/下的多个模块,而classpath:com/demo/module*.xml 表示加载com/demo/下的多个module开头,.xml结尾的配置文件。
  • 资源路径匹配符
    在这里插入图片描述
  1. 资源加载器
    在这里插入图片描述
  • ResourcePatternResolver接口:继承interface ResourcePatternResolver extends ResourceLoader,支持带资源类型前缀及Ant风格的表达式。
  • PathMatchingResourcePatternResolver:实现class PathMatchingResourcePatternResolver implements ResourcePatternResolver,为Spring提供的标准实现类。
  • Tips:项目打包后生成jar时,使用ResourceLoader().getResource(“classpath:<your_path>”).getFile() 可能会抛出FileNotFoundException,可以采用ResourceLoader().getResource(“classpath:<your_path>”).getInputStream() 方法读取。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值