resources

Resources(com.ibatis.common.resource.*)   
Resources 类为从类路径中加载资源,提供了易于使用的方法。处理 ClassLoader 是一项  
富于挑战的工作,尤其是应用服务器/容器的情况下。Resources 类试图简化这些工作。   
Resources 类常用于以下几种情况:   
? 从类路径加载 SQL Map 配置文件(如 sqlMap-config.xml)。   
? 从类路径加载 DAO Manager 配置文件(如 dao.xml)。   
? 从类路径加载各种.properties 文件。   
加载一个资源有很多方式,包括:   
? 对于简单的只读文本数据,加载为 Reader。   
? 对于简单的只读二进制或文本数据,加载为 Stream。   
? 对于可读写的二进制或文本文件,加载为 File。   
? 对于只读的配置属性文件,加载为 Properties。   
? 对于只读的通用资源,加载为 URL。   
按以上的顺序,Resources 类加载资源的方法如下:   
Reader getResourceAsReader(String resource);   
Stream getResourceAsStream(String resource);   
File getResourceAsFile(String resource);   
Properties getResourceAsProperties(String resource);   
Url getResourceAsUrl(String resource);   
在以上每个方法中,加载资源和加载 Resources 类的为同一个 ClassLoader,或者,如果  
失败,将使用系统的 ClassLoader。在某些环境下(比如某些应用服务器),ClassLoader 可能  
是个麻烦事,您可以指定所使用的 ClassLoader(比如使用加载应用的 ClassLoader)。上面每  
个方法都有相应把 ClassLoader 作为参数的方法。它们是:   
Reader getResourceAsReader (ClassLoader classLoader, String resource);   
Stream getResourceAsStream (ClassLoader classLoader, String resource);   
File getResourceAsFile (ClassLoader classLoader, String resource);   
Properties getResourceAsProperties (ClassLoader classLoader, String resource);   
Url getResourceAsUrl (ClassLoader classLoader, String resource);   
以上方法的 resource 参数名称应该是全限定名,加上全文件/资源名。例如,如果在类  
路径中有资源“com.domain.mypackage.MyPropertiesFile.properties”,您使用下面的代码加载  
http://www.ibatis.com                                   Clinton Begin 著 刘涛([email protected]) 译   
开发指南                          iBATIS SQL Maps                             Page 59 of 62   
资源为 Properties(注意,资源名前面不需要斜杠/)。   
String resource = “com/domain/mypackage/MyPropertiesFile.properties”;   
Properties props = Resources.getResourceAsProperties (resource);   
同样地,您可以从类路径加载 SQL Map 配置文件为一个 Reader。假设它在类路径的  
properties 目录下(properties.sqlMap-config.xml)。   
String resource = “properties/sqlMap-config.xml”;   
Reader reader = Resources.getResourceAsReader(resource);   
SqlMapClient sqlMap = XmlSqlMapBuilder.buildSqlMap(reader);   

猜你喜欢

转载自blog.csdn.net/pursure123/article/details/79244868