zoukankan      html  css  js  c++  java
  • Spring之ResourceLoader加载资源

    Resource与ResourceLoader对比

    1、Resource接口定义了应用访问底层资源的能力。

    • 通过FileSystemResource以文件系统绝对路径的方式进行访问;
    • 通过ClassPathResource以类路径的方式进行访问;
    • 通过ServletContextResource以相对于Web应用根目录的方式进行访问。

      在获取资源后,用户就可以通过Resource接口定义的多个方法访问文件的数据和其他的信息:如可以通过getFileName()获取文件名,通过getFile()获取资源对应的File对象,通过getInputStream()直接获取文件的输入流。此外,还可以通过createRelative(String relativePath)在资源相对地址上创建新的文件。

    2、ResourceLoader接口提供了一个加载文件的策略。它提供了一个默认的实现类DefaultResourceLoader,获取资源代码如下:

     1 @Override
     2 public Resource getResource(String location) {
     3     Assert.notNull(location, "Location must not be null");
     4     if (location.startsWith("/")) {
     5         return getResourceByPath(location);
     6     }
     7     else if (location.startsWith(CLASSPATH_URL_PREFIX)) {
     8         return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
     9     }
    10     else {
    11         try {
    12             // Try to parse the location as a URL...
    13             URL url = new URL(location);
    14             return new UrlResource(url);
    15         }
    16         catch (MalformedURLException ex) {
    17             // No URL -> resolve as resource path.
    18             return getResourceByPath(location);
    19         }
    20     }
    21 }
    1 protected Resource getResourceByPath(String path) {
    2     return new ClassPathContextResource(path, getClassLoader());
    3 }
  • 相关阅读:
    Dubbo教程:入门到实战
    阿里面试Java程序员都问些什么?
    Canon MF113W激光打印机双面打印方法
    MacBook Pro App Store无法下载和更新软件解决方案
    收不到Win10正式版预订通知?一个批处理搞定
    创业公司失败的20大原因:没市场需求排第一
    最新版本sublime text3注册码
    Spring MVC 知识点整理
    Nginx子域名配置
    Install Local SQL In Mac OS
  • 原文地址:https://www.cnblogs.com/luyanliang/p/5566574.html
Copyright © 2011-2022 走看看