Spring 中读取文件-ResourceLoaderAware

Spring 中读取文件-ResourceLoaderAware

概述

  • Spring ResourceLoader为我们提供了一个统一的getResource()方法来通过资源路径检索外部资源。从而将资源或文件(例如文本文件、XML文件、属性文件或图像文件)加载到Spring应用程序上下文中的不同实现

    资源(Resource)接口

  • Resource是Spring中用于表示外部资源的通用接口。
  • Spring为Resource接口提供了以下6种实现。
  • UrlResource
  • ClassPathResource
  • FileSystemResource
  • ServletContextResource
  • InputStreamResource
  • ByteArrayResource
  • 我们可以指定不同的前缀来创建路径以从不同位置加载资源
    • 1159210-20191025105100598-2085940755.png

ResourceLoader

  • getResource()方法将根据资源路径决定要实例化的Resource实现。 要获取ResourceLoader的引用,请实现ResourceLoaderAware接口。
Resource banner = resourceLoader.getResource("file:c:/temp/filesystemdata.txt");

ApplicationContext加载资源

  • 在Spring中,所有应用程序上下文都实现ResourceLoader接口。因此,所有应用程序上下文都可用于获取资源实例。
  • 要获取ApplicationContext的引用,请实现ApplicationContextAware接口。
Resource banner = ctx.getResource("file:c:/temp/filesystemdata.txt");

在springboot中使用示例

@Component
public class CustomResourceLoader implements ResourceLoaderAware {
    @Autowired
    private ResourceLoader resourceLoader;


    public void showResourceData() throws IOException
    {
        //This line will be changed for all versions of other examples
        Resource banner = resourceLoader.getResource("file:E:\\refreshlog\\log1.txt");

        InputStream in = banner.getInputStream();

        BufferedReader reader = new BufferedReader(new InputStreamReader(in));

        while (true) {
            String line = reader.readLine();
            if (line == null) {
                break;
            }
            System.out.println(line);
        }
        reader.close();
    }

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        try {
            showResourceData();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

参考

  • Spring ResourceLoaderAware – Read file in Spring
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值