Resources (针对于资源文件的统一接口)
A、UrlResource:URL 对应的资源,根据一个 URL 地址即可获取
B、ClassPathResource:获取类路径下的资源
C、FileSystemResource:获取文件系统里面的资源
D、ServletContextResource:ServletContext 封装的资源,用于访问 ServletContext 环境下的资源
E、InputStreamResource:获取输入流封装的资源
F、ByteArrayResource:获取字节数组封装的资源
ApplicationContext实现了所有的接口,因此可以通过实现ApplicationContextAware 接口或得applicationContext,然后获得Resource
创建bean MyResource 实现ApplicationContextAware接口
package resource;
import java.io.IOException;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.Resource;
public class MyResource implements ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext arg0)
throws BeansException {
// TODO Auto-generated method stub
this.applicationContext = arg0;
}
public void resource() throws IOException {
Resource resource = applicationContext.getResource("spring-resource.xml");
System.out.println(resource.getFilename());
System.out.println(resource.contentLength());
}
}
创建spring配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"
default-autowire="byName">
<bean id="myResource" class="resource.MyResource" ></bean>
</beans>
测试
package test.resouce;
import java.io.IOException;
import ioc.injection.service.InjectionService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import resource.MyResource;
@RunWith(BlockJUnit4ClassRunner.class)
public class TestResource {
private ClassPathXmlApplicationContext context;
@Test
public void testCons() throws IOException {
context = new ClassPathXmlApplicationContext("spring-resource.xml");
MyResource mr =(MyResource) context.getBean("myResource");
mr.resource();
}
}