Your Ad Here
首页 | 编程语言 | 网站建设 | 游戏天堂 | 冲浪宝典 | 网络安全 | 操作系统 | 软件时空 | 硬件指南 | 病毒相关 | IT 认证
软讯网络 > 编程语言 > Java > 使用Spring中的Resource接口隔离对文件系统的依赖
【标  题】:使用Spring中的Resource接口隔离对文件系统的依赖
【关键字】:Spring,Resource
【来  源】:http://www.blogjava.net/stingh711/archive/2006/11/19/82015.html

使用Spring中的Resource接口隔离对文件系统的依赖

Your Ad Here

在项目中,经常要用到读系统文件.在项目的遗留代码中,都是在系统启动是传入一个APP_HOME,然后根据相对路径去读文件.这样做的缺点是比较难测试,而且自动化的测试更难.

比如说有这样一个类Server,要根据server.properties来初始化,一开始的代码是这样的:

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

/**
* @author sting
*/
public class Server {
private static final String FILE = "conf" + File.separator + "server.properties";

public void initial() throws IOException {
FileInputStream in = new FileInputStream(System.getProperty("APP_HOME") + File.separator + FILE);
Properties properties = new Properties();
properties.load(in);
// initial
}
}

文件路径和文件名都是hard code,很难测试. 我们首先把initial()重构一下,代码如下:


public void initial(InputStream in) throws IOException {
Properties properties = new Properties();
properties.load(in);
// initial
}

至少,测试时,我们可以传进来自己的InputStream,也可以方便的时候测试用的server.properties,或者干脆使用内联的文件,代码如下:

class ServerTest extends TestCase {
private Server server;

public void setUp() throws Exception {
this.server = new Server();
}

public void testInitial() throws Exception {
String serverProperties = "port=8080\n" +
"run_mode=normal";
InputStream in = new ByteArrayInputStream(serverProperties.getBytes());

this.server.initial(in);
// assert
}
}

但是,在实际工作的代码中,文件名和路径依然要hard code进代码中.这时,我们可以使用spring中的Resource接口来进一步改进我们的代码.

public class Server {
private Resource resource;

public void setResource(Resource r) {
this.resource = r;
}

public void initial() throws IOException {
Properties properties = new Properties();
properties.load(this.resource.getInputStream());
// initial
}
}

再加一段spring的配置文件:

<beans>
<bean id="server" class="Server">
<property name="resource" value="classpath:server.properties"/>
</bean>
</beans>

这样,Server的代码完全与文件的具体路径和文件名无关,仅仅用配置文件就可以指定,表达更清楚,也更易于测试.

当然,仅限于已经使用spring的项目.

关于设计:【上一篇】
探索Java NIO的历程:【下一篇】
【相关文章】
  • 11月17日更新视频Spring3,Struts4,很久不做事了
  • 在Spring中如何使用Freemarker
  • Struts之Message Resources用法
  • Spring+Struts+Hibernate+Buffalo构建支持Ajax的轻量级J2EE框架
  • 初识J2EE框架(struts+hibernate+spring)
  • Spring OSGi规范(v0.7)中文版
  • 《深入Spring2》第五章“AOP及在Spring中的应用”的电子版出来了
  • 把DWR的配置写到Spring的配置文件里(Spring2 新特性-自定义schema初体验)
  • Java 週報 > 爪哇教室> 第一個Spring程式
  • 基于Spring+JDBC的用户管理系统
  • 【随机文章】
  • 技术沙龙.:主题为《代码解析Castle(IOC)应用实例 -开源CMS 系统Cuyahoga》
  • unix系统命令大全
  • java读文件的一点见解
  • Lucene 全文检索实践四
  • 用文本+ASP打造新闻发布系统(二)新闻添加
  • 微软认证证书的有效期有多长?
  • 计算机系统生命周期中的安全和计划
  • Win2000+Apache+MySql+PHP4+PERL安装使用小结
  • 网站流量统计组件:JoomlaStats 中文版
  • 从数据源取回数据--Command 物件简介
  • 【相关评论】
    没有相关评论
    【发表评论】
    姓名:
    邮件:
    随机码*
    评论*
          
    |  首 页  |  版权声明  |  联系我们   |  网站地图  |
    CopyRight © 2004-2007 bbb软讯网络 All Rigths Reserved.