SpringMVC读取资源文件的几种方式

本文介绍了Spring IoC容器的启动过程,包括加载资源文件、解析资源文件和注册BeanDefinition。重点讲解了Spring中Resource和ResourceLoader接口在加载资源文件时的作用,以及ClassPathResource和DefaultResourceLoader的加载过程。还提到了如何通过自定义协议解析器进行扩展。
摘要由CSDN通过智能技术生成

前面介绍了Spring的一些基础知识和简单的用法,本篇开始分析Spring的IoC容器。BeanFactory是IoC容器的基础,所以接下来的分析都是基于BeanFactory的。

IoC启动过程:

启动
加载资源文件
解析资源文件
注册BeanDefinition
结束
IoC容器的启动可分为三步,加载资源文件、解析资源文件、注册BeanDefinition。本篇分析资源文件加载过程。

Spring中资源文件加载主要有两个接口,Resource和ResourceLoader,前者提供了对资源文件的定位、是否存在、是否可读、是否打开、是否文件、获取URL,获取File、获取FileName等一系列功能。后者提供了Resource对象获取,自定义资源文件协议解析等功能。加载资源文件的过程会涉及到类加载机制,且不是我们分析IoC容器的重点,所以本篇不会做太多深入的分析。测试类

import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;

import java.io.IOException;

public class MyTest {

    @Test
    public void test1() {
        // 从资源文件夹下加载
        Resource resource = new ClassPathResource("v2/day01.xml");
        print(resource);

    }

    @Test
    public void test2() {
        // 使用类信息加载
        Resource resource = new ClassPathResource("day01.xml", MyTest.class);
        print(resource);

    }

    @Test
    public void test3() {
        // 使用类加载器从资源文件夹下加载
        Resource resource = new ClassPathResource("v2/day01.xml", MyTest.class.getClassLoader());
        print(resource);
    }

    @Test
    public void test4() {
        // 使用DefaultResourceLoader加载
        Resource resource = new DefaultResourceLoader().getResource("v2/day01.xml");
        print(resource);
    }

    // 打印资源文件内容
    public void print(Resource resource) {
        byte[] read = new byte[10000];
        try {
            resource.getInputStream().read(read, 0, read.length);
            System.out.println(new String(read));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

运行测试类,将会打印day01.xml的内容。注意资源文件的路径

先分析ClassPathResource的加载过程,再DefaultResourceLoader的加载过程

1. ClassPathResource对象创建过程
创建ClassPathResource对象

public ClassPathResource(String path, @Nu
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值