思考: Java标准URL资源访问方式不能满足吗? Spring是怎么资源访问的?
答: java 提供的标准URL 和标准URL处理器并不能很好地满足我们对各种底层资源的访问,比如:没有标准化URL 实现访问相对类路径或者相对 ServletContext 环境下的各种资源,即使要用URL方式,也需要做特别处理,很不方便。为此,Spring自己定义了Resources接口,更好更方便地实现了对底层资源的访问。
思考:Spring提供了几种资源访问方式呢?
答: Spring资源访问有四种方式,如下图:
- Resource接口
它为底层资源访问提供了一套更好的机制, Resource接口继承了InputStreamSource 接口,Resources接口提供了多种方法,如:getInputStream(),getURL(), getFile(),exists()等,它不仅被spring大量使用,而且可以做为URL访问底层资源的有效替代,单独使用。Spring 还提供了多种开箱即用的Resource实现类,如下:
//使用FileSystemResource获取资源方法 Resource resource = new FileSystemResource("D:\\test.txt"); System.out.println(resource.getFilename());
- ResourceLoader接口
Spring为了更方便的获取资源,弱化程序员对各个Resource接口的实现类的感知,定义了另一个ResourceLoader接口,该接口的getResource(String location)方法可以用来获取资源,它的DefaultResourceLoader实现类可以适用于所有的环境,可以返回ClassPathResource、UrlResource等。
ResourceLoader loader = new DefaultResourceLoader(); //类路径资源 Resource resource = loader.getResource("classpath:test.txt"); System.out.println(resource.getFilename()); //URL资源 resource = loader.getResource("http://xx.xx.com"); System.out.println(resource.getURL());
- ApplicationContext
ApplicationContext实例实现了ResourceLoader接口,不需要自己创建Resource实现类,直接使用applicationContext.getResource()获取资源。
Resource res = applicationContext.getResource("file:E:\\resource.txt"); System.out.println(res.getFilename());
- 资源注入到bean中
把资源注入到resource.xml的bean定义中
<bean id="manager" class="com.spring.resource.Manager"> <property name="resource"> <value>classpath:test.txt</value> </property> </bean>
调用
ApplicationContext context = new ClassPathXmlApplicationContext("classpath: resource.xml"); Manager manager = (Manager) context.getBean("manager ");