在之前的操作之中可以发现,虽然Resource的子类可以利用了字符串格式进行了隐藏,但是此时的代码之中发现ResourceLoader跟我的开发没有任何的关系.如果真的开发只关系Resource一个接口就够了,
为了解决Resource与ResourceLoader的操作关系耦合问题,那么在Spring设计的时候考虑到数据的自动转型问题,也就是说利用注入的操作模式,就可以让ResourceLoader消失了.
范例:编写一个资源处理类
package cn.resource.util;
import org.springframework.core.io.Resource;
public class ResourceBean {
private Resource resource;
public void setResource(Resource resource) {
this.resource = resource;
}
public Resource getResource() {
return resource;
}
}
要想实现数据资源的注入操作,那么就必须编写applicationCpntext.xml文件,在这个文件里面定义所需要的资源.
范例:在applocationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd">
<bean id="rb" class="cn.resource.util.ResourceBean">
<property name="resource" value="file:e:\\test.xml"></property>
</bean>
</beans>
范例:测试代码
package cn.resource.test;
import java.io.IOException;
import java.util.Scanner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.resource.util.ResourceBean;
public class TestResource {
public static void main(String[] args) throws IOException {
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
ResourceBean rebBean=ctx.getBean("rb",ResourceBean.class);
Scanner scanner=new Scanner(rebBean.getResource().getInputStream());
scanner.useDelimiter("\n");
while (scanner.hasNext()) {
System.out.println(scanner.next());
}
}
}
利用了配置文件的方式进行处理的时候,用户关系的只是Resource一个接口的使用,而ResourceLoader接口的作用被Spring封装起来了
而且最为方便的是,在Spring里面允许用户设置资源数组.
范例:修改程序类
package cn.resource.test;
import java.io.IOException;
import java.util.Iterator;
import java.util.Scanner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.Resource;
import cn.resource.util.ResourceList;
public class TestResource {
public static void main(String[] args) throws IOException {
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
ResourceList rebBean=ctx.getBean("rblist",ResourceList.class);
Iterator<Resource> it=rebBean.getResource().iterator();
while(it.hasNext()){
Scanner scanner=new Scanner(it.next().getInputStream());
scanner.useDelimiter("\n");
while (scanner.hasNext()) {
System.out.println(scanner.next());
}
}
}
}
<bean id="rblist" class="cn.resource.util.ResourceList">
<property name="resource">
<list>
<value>file:e:\\练习.txt</value>
<value>file:e:\\练习.txt</value>
</list>
</property>
</bean>
利用Spring读取外部文件的时候它的设计要比使用IO包更加容易