Resources的使用方式

来源:互联网 发布:2016年云计算政策 编辑:程序博客网 时间:2024/06/01 16:32

转自:http://blog.csdn.net/dongwujing/article/details/7751057


  1. Resources(com.ibatis.common.resource.*)   
  2. Resources 类为从类路径中加载资源,提供了易于使用的方法。处理 ClassLoader 是一项富于挑战的工作,尤其是应用服务器/容器的情况下。Resources 类试图简化这些工作。
  3.    
  4. Resources 类常用于以下几种情况:   
  5. ? 从类路径加载 SQL Map 配置文件(如 sqlMap-config.xml)。   
  6. ? 从类路径加载 DAO Manager 配置文件(如 dao.xml)。   
  7. ? 从类路径加载各种.properties 文件。   
  8. 加载一个资源有很多方式,包括:   
  9. ? 对于简单的只读文本数据,加载为 Reader。   
  10. ? 对于简单的只读二进制或文本数据,加载为 Stream。   
  11. ? 对于可读写的二进制或文本文件,加载为 File。   
  12. ? 对于只读的配置属性文件,加载为 Properties。   
  13. ? 对于只读的通用资源,加载为 URL。   
  14. 按以上的顺序,Resources 类加载资源的方法如下:   
  15. Reader getResourceAsReader(String resource);   
  16. Stream getResourceAsStream(String resource);   
  17. File getResourceAsFile(String resource);   
  18. Properties getResourceAsProperties(String resource);   
  19. Url getResourceAsUrl(String resource);   

  1. 在以上每个方法中,加载资源和加载 Resources 类的为同一个 ClassLoader,或者,如果失败,将使用系统的 ClassLoader。在某些环境下(比如某些应用服务器),ClassLoader 可能是个麻烦事,您可以指定所使用的 ClassLoader(比如使用加载应用的 ClassLoader)。上面每个方法都有相应把 ClassLoader 作为参数的方法。它们是:   
  2. Reader getResourceAsReader (ClassLoader classLoader, String resource);   
  3. Stream getResourceAsStream (ClassLoader classLoader, String resource);   
  4. File getResourceAsFile (ClassLoader classLoader, String resource);   
  5. Properties getResourceAsProperties (ClassLoader classLoader, String resource);   
  6. Url getResourceAsUrl (ClassLoader classLoader, String resource);   

  7. 以上方法的 resource 参数名称应该是全限定名,加上全文件/资源名。例如,如果在类路径中有资源“com.domain.mypackage.MyPropertiesFile.properties”,您使用下面的代码加载  
  8. http://www.ibatis.com 
  9. Clinton Begin 著 刘涛(toleu@21cn.com) 译   
  10. 开发指南                          iBATIS SQL Maps                             Page 59 of 62   
  11. 资源为 Properties(注意,资源名前面不需要斜杠/)。   
  12. String resource = “com/domain/mypackage/MyPropertiesFile.properties”;   
  13. Properties props = Resources.getResourceAsProperties (resource);   
  14. 同样地,您可以从类路径加载 SQL Map 配置文件为一个 Reader。假设它在类路径的  
  15. properties 目录下(properties.sqlMap-config.xml)。   
  16. String resource = “properties/sqlMap-config.xml”;   
  17. Reader reader = Resources.getResourceAsReader(resource);   
  18. SqlMapClient sqlMap = XmlSqlMapBuilder.buildSqlMap(reader);   

0 0