Resource

Resource 接口定义

public interface Resource extends InputStreamSource {    /**     * 返回此资源的 URL 句柄     */    URL getURL() throws IOException;    /**     * 返回此资源的 URI 句柄     */    URI getURI() throws IOException;    /**     * 返回此资源的 File 句柄     */    File getFile() throws IOException;    /**     * 创建此资源的关联资源     */    Resource createRelative(String relativePath) throws IOException;}public interface InputStreamSource {    /**     * 返回底层资源内容的 InputStream     */    InputStream getInputStream() throws IOException;}

内置 Resource 实现者

  • UrlResource —— 封装 java.net.URL,用于访问通过URL访问的任何对象,例如 file:http:ftp:
  • ClassPathResource —— 使用线程上下文类加载器、给定的类加载器或给定的类从类路径加载资源。如 classpath:
  • FileSystemResource —— 从文件系统加载资源
  • ServletContextResource —— 从 Web 应用根目录的相对路径中加载资源,支持 URL、流、File(资源位于文件系统)访问
  • InputStreamResource —— 在没有特定的资源实现时使用
  • ByteArrayResource —— 从任何给定的字节数组加载资源

ResourceLoader

  • 返回资源类型确认
//对于 ClassPath ApplicationContext, 返回 ClassPathResource//对于 FileSystem ApplicationContext, 返回 FileSystemResource//对于 WebApplicationContext, 返回 ServletContextResourceResource template = ctx.getResource("some/resource/path/myTemplate.txt");//指定 classpath:,返回 ClassPathResourceResource template = ctx.getResource("classpath:some/resource/path/myTemplate.txt");//指定 file:、http:,返回 UrlResourceResource template = ctx.getResource("file:///some/resource/path/myTemplate.txt");Resource template = ctx.getResource("https://myhost.com/resource/path/myTemplate.txt");

与 ApplicationContext 协作

ApplicationContext ctx = new ClassPath ApplicationContext("conf/appContext. ");//注意:FileSystem ApplicationContext 强制将 FileSystemResource 路径当作相对路径ApplicationContext ctx = new FileSystem ApplicationContext("conf/appContext. ");//如要使用绝对路径,推荐使用 file: 形式的 UrlResourceApplicationContext ctx = new FileSystem ApplicationContext("file:///conf/context. ");
收藏 打印