2016/1/16 13:53:12
1.Resources
- 针对于资源文件的统一接口
- Resources
- UrlResource:URL对应的资源,根据一个URL地址即可创建
- ClassPathResource:获取类路径下的资源文件
- FileSystemResource:获取文件系统里面的资源
- ServletContextResource:ServletContext封装的资源,用于访问ServletContext环境下的资源
- InputStreamResource:针对输入流封装的资源
- ByteArrayResource:针对于字节数封装的资源
2.ResourceLoader
XML:spring-resource.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<bean id="resource" class="com.zjx.resource.Resource"></bean>
</beans>
bean类:
package com.zjx.resource;
import java.io.IOException;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class Resource implements ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext arg0)
throws BeansException {
this.applicationContext = arg0;
}
public void resource() throws IOException{
org.springframework.core.io.Resource resource = this.applicationContext.getResource("classpath:jdbc.properties");
System.out.println(resource.getFilename());
System.out.println(resource.contentLength());
}
}
测试:
package com.zjx.interfaces.test;
import java.io.IOException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
import com.zjx.resource.Resource;
@RunWith(BlockJUnit4ClassRunner.class)
public class TestResource extends UnitTestBase{
public TestResource() {
super("spring-resource.xml");
}
@Test
public void test() throws IOException{
Resource resource = super.getBean("resource");
resource.resource();
}
}
本文介绍了Spring框架中资源文件的六种加载方式,包括通过URL、类路径、文件系统、ServletContext、输入流及字节数组等方式加载资源。并提供了一个具体的实现示例,展示了如何在实际应用中使用这些资源加载方式。
6761

被折叠的 条评论
为什么被折叠?



