Spring源码分析之Resource

前言

Spring使用Resource接口来抽象所有使用的底层资源,对不同的来源有不同的实现,如Classpath资源(ClassPathResource),文件资源(FileSystemResource)等。
class文件、properties文件、yml文件都可以看做Resource。

Resurce

相关类图如下

简单使用

复制import java.io.IOException;
import java.nio.charset.StandardCharsets;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.StreamUtils;

public class TestResource {

  public static void main(String[] args) throws IOException {
    Resource resource = new ClassPathResource("abc.txt");
    System.out.println(resource.exists());//资源是否存在
    System.out.println(resource.getFile().getAbsolutePath());//绝对路径
    String content = StreamUtils.copyToString(resource.getInputStream(), StandardCharsets.UTF_8);
    System.out.println(content);//资源内容
  }

}

一般不会直接创建Resource对象,而是通过资源加载器(ResourceLoader)来获取(简单工厂模式的使用)。

ResourceLoader

相关类图如下

默认实现为DefaultResourceLoader,通过不同的路径格式来创建不同类型的Resource,如果以classpath:开头,那么就创建ClassPathResource。

复制import java.io.IOException;
import java.nio.charset.StandardCharsets;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.StreamUtils;

public class TestResourceLoader {

  public static void main(String[] args) throws IOException {
    ResourceLoader resourceLoader = new DefaultResourceLoader();
    Resource resource = resourceLoader.getResource("classpath:abc.txt");
    String content = StreamUtils.copyToString(resource.getInputStream(), StandardCharsets.UTF_8);
    System.out.println(content);
  }
}

ResourcePatternResolver是一种更加强大的ResourceLoader,在ResourceLoader的基础上增加了递归查询目录和jar包及通配符查询的功能,默认实现为PathMatchingResourcePatternResolver。

复制import java.io.IOException;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

public class TestResourcePatternResolver {

  public static void main(String[] args) throws IOException {
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    Resource[] resources = resolver.getResources("classpath*:**/*.class");
    for (Resource resource : resources) {
      System.out.println(resource.getFilename());
    }
  }

}

查询classpath下所有的class文件,包含内部类。

在Spring中的使用

Spring在扫描指定package下的所有包含Component注解的class时,就是通过PathMatchingResourcePatternResolver来实现的。

posted @   strongmore  阅读(118)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
历史上的今天:
2021-05-05 java实现单例模式的各种写法
点击右上角即可分享
微信分享提示