zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    Python操作 RabbitMQ、Redis、Memcache、SQLAlchemy
    Twsited异步网络框架
    MySQL-python模块
    python3安装Fabric模块
    PInvoke.net Visual Studio Extension
    资源下载站
    WPF RTSP存储到一个文件中的位置
    Windows 7 中未能从程序集System.ServiceModel
    无法在WEB服务器上启动调试,Web 服务器配置不正确
    CS0016: 未能写入输出文件“c:WINDOWSMicrosoft.NETFramework.。。”--“拒绝访问
  • 原文地址:https://www.cnblogs.com/frankltf/p/11736830.html
Copyright © 2011-2022 走看看