Spring 中读取文件-ResourceLoaderAware

Spring 中读取文件-ResourceLoaderAware

概述

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

资源(Resource)接口

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

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
posted @ 2019-10-25 10:55  技术-刘腾飞  阅读(1873)  评论(0编辑  收藏  举报