Resource对象是针对于资源文件的统一接口,即通过applicationContext.getResource方法我们可以将某个资源文件转化为Resource对象供我们使用
它的获取方法常用的有四种:classpath、file、http、none
第一步:建立xml以及测试类和资源文件config.txt
xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="moocResource" class="com.imooc.resource.MoocResource"></bean>
</beans>
测试类
package com.imooc.resource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.Resource;
public class TestResource {
public static void main(String[] args) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("spring-resource.xml");
Resource resource=ctx.getResource("classpath:config.txt");
Resource resource2=ctx.getResource("file:E:\\eclipse\\Spring\\src\\config.txt");
// Resource resource3=ctx.getResource("http:输入浏览器的网址即可");
Resource resource4=ctx.getResource("config.txt");
System.out.println(resource.getFilename());
System.out.println(resource2.getFilename());
//System.out.println(resource3.getFilename());
System.out.println(resource4.getFilename());
第一种方法:classpath指的是当前项目是否在javabuildpath下的Source中,这种方法与默认什么都不填实质是一样的
第二种方法:输入文件在文件系统中的位置
第三种方法:输入文件在网络中位置