Spring中Resource和ResourceLoader

Spring对物理资源的访问方式抽象成Resource,我们可以通过Spring提供的接口来访问磁盘文件等数据,Spring力争提供一个统一的接口来给编程人员使用。下面我们来看看如何使用Resource接口:

Resource r = new ClassPathResource("r.txt");
File file = r.getFile();
System.out.println(file.length());

再来看看一个例子:

FileSystemResource fileSystemResource = new FileSystemResource("d:/a.txt");
OutputStream outputStream = fileSystemResource.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
bufferedWriter.write("Hello World");
bufferedWriter.flush();
outputStream.close();
bufferedWriter.close();

看到这里,应该可以知道Resource是做什么用的了,那我们需要来看看Resource的类图结构了,这样就能具体的知道Resource能提供哪些功能了:

 下面的子类很多,用UML工具画出来不好看,我直接从eclipse里截图,看起来更全面:

下面来看看ResourceLoader有关的类图

SpringResourceLoader是一个接口,提供了一种简单的方式来加载资源文件,如XML配置文件、Properties文件、图片等。它提供了一种统一的方式来访问资源,不需要关心资源文件存储在哪里,比如在文件系统、在类路径下、在Web应用程序上下文等。 以下是一个简单的ResourceLoader用法示例: ```java import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; public class MyResourceLoader { private ResourceLoader resourceLoader; public MyResourceLoader(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } public void loadResource() throws IOException { // 加载一个资源文件 Resource resource = resourceLoader.getResource("classpath:my-resource.xml"); // 获取资源文件的输入流 InputStream is = resource.getInputStream(); // 处理资源文件 // ... } } ``` 在上面的示例,我们首先定义了一个MyResourceLoader类,它依赖于ResourceLoader接口。然后我们使用ResourceLoader接口的`getResource()`方法加载一个名为“my-resource.xml”的资源文件,并获取它的输入流。最后,我们可以使用输入流来处理资源文件的内容。 Spring提供了多种ResourceLoader实现,如ClassPathResourceLoader、FileSystemResourceLoader、ServletContextResourceLoader等。我们可以根据不同的情况选择不同的ResourceLoader实现。例如,在Web应用程序,我们可以使用ServletContextResourceLoader来加载Web应用程序上下文的资源文件。 ```java import org.springframework.core.io.Resource; import org.springframework.web.context.support.ServletContextResourceLoader; public class MyResourceLoader { private ServletContextResourceLoader resourceLoader; public MyResourceLoader(ServletContextResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } public void loadResource() throws IOException { // 加载一个资源文件 Resource resource = resourceLoader.getResource("/WEB-INF/my-resource.xml"); // 获取资源文件的输入流 InputStream is = resource.getInputStream(); // 处理资源文件 // ... } } ``` 在上面的示例,我们使用了ServletContextResourceLoader来加载一个Web应用程序上下文的资源文件。在调用getResource()方法时,我们可以使用相对于Web应用程序根目录的路径来指定资源文件的位置。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值