Spring2.0简明手册(系列之二 Resource的配置及使用)
版权声明:原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。http://robert.blog.51cto.com/374512/75981 | ||||||||||||||||||
这一节总结一下Spring关于资源的访问。 1.基础知识--3个重要接口 1)Resource 接口 是对底层资源的封装,为资源的访问提供更加方便的接口。 2)ResourceLoader 接口Resource不仅被Spring自身大量地使用,它也非常适合在你自己的代码中独立作为辅助类使用。 用户代码甚至可以在不用关心Spring其它部分的情况下访问资源。这样的确会造成代码与Spring之间的耦合,但也仅仅是与很少量的辅助类耦合。这些类可以作为比 URL 更有效的替代,而且与为这个目的而使用其它类库基本相似。 主要的实现类: UrlResource ClassPathResource FileSystemResource ServletContextResource InputStreamResource ByteArrayResource 实现这个接口的类能够得到Resource实例。 3)ResourceLoaderAware 接口主要的实现类:所有的application context。 实现这个接口的类,表示希望拥有一个ResourceLoader的引用。 当实现了 ResourceLoaderAware接口的类部署到application context(比如受Spring管理的bean)中时,它会被application context识别为 ResourceLoaderAware。接着,application context会调用setResourceLoader(ResourceLoader)方法,并把自身作为参数传入该方法(记住,所有Spring里的application context都实现了ResourceLoader接口)。 2.实际运用 1)Bean中使用资源: 通常只需让bean暴露所需的 Resource 属性,通过依赖注入Resource实例。 <!--强制使用ClassPathResource--> <property name="template" value="classpath:some/resource/path/myTemplate.txt"> <!--强制使用UrlResource访问本地文件资源--> <property name="template" value="file:/some/resource/path/myTemplate.txt"/> <!--Resource的类型取决于ApplicationContext的类型--> <property name="template" value="some/resource/path/myTemplate.txt"/> 2)ApplicationContext中使用资源 (1)手动构建ApplicationContext时,传入资源路径标识符(标识资源路径的字符串) // Resource的类型取决于ApplicationContext的类型 ApplicationContext ctx = new ClassPathXmlApplicationContext("conf/appContext.xml"); ApplicationContext ctx = new FileSystemClassPathXmlApplicationContext("conf/appContext.xml"); // 强制使用ClassPathResource ApplicationContext ctx = new FileSystemXmlApplicationContext("classpath:conf/appContext.xml"); 这里我们是将ApplicationContext作为ResourceLoader来使用,别忘了getResource()方法来自于ResourceLoader接口。 // 强制使用ClassPathResource Resource template = ctx.getResource("classpath:some/resource/path/myTemplate.txt"); // 强制使用UrlResource访问本地文件资源 Resource template = ctx.getResource("file:/some/resource/path/myTemplate.txt"); // 强制使用UrlResource访问web资源 Resource template = ctx.getResource("http://myhost.com/resource/path/myTemplate.txt"); // Resource的类型取决于ApplicationContext的类型 Resource template = ctx.getResource("some/resource/path/myTemplate.txt"); 3.资源路径标识符(Resource Path Identifier) 资源路径标识符(RPI),自己发明的一个词,就是标识资源路径的字符串。 从RPI到 Resource 的转换规则(资源的访问策略)
本文出自 “点滴积累_勤耕不辍” 博客,请务必保留此出处http://robert.blog.51cto.com/374512/75981 本文出自 51CTO.COM技术博客 |


robert.luo77
博客统计信息
热门文章
最新评论
友情链接