Spring中的资源定义:Resource
此接口的全名为:org.springframework.core.io.Resource
比较常用的资源定义的实现类为:
1.ClassPathResource 从classpath中读取
2.FileSystemResource 从文件系统中读取
3.UrlResource 从指定URL中读取
4.ServletContextResource 必须要在web环境下使用
1.ClassPathResource
@Test
public void testClassPathResource_1() throws Exception {
// 指定一个相对于classpath根目录的相对路径
Resource resource = new ClassPathResource(//
"com/winner/resource/applicationContext.xml");
System.out.println(resource.getFile().getAbsolutePath());
} @Test
public void testClassPathResource_2() throws Exception {
// 指定一个相对于指定类的相对路径,以下表示配置文件和MainTest在相同的路径下
Resource resource = new ClassPathResource("applicationContext.xml", MainTest.class);
System.out.println(resource.getFile().getAbsolutePath());
}
2.FileSystemResource
@Test
public void testFileSystemResource() throws Exception {
// 指定一个资源路径,推荐写绝对路径,以下表示在C盘下
Resource resource = new FileSystemResource("c:/applicationContext.xml");
System.out.println(resource.getFile().getAbsolutePath());
}
3.UrlResource
@Test
public void testUrlResource() throws Exception {
// 指定一个URL,如file://...或是http://...等等
Resource resource = new UrlResource("file://c:/applicationContext.xml");
System.out.println(resource.getFile().getAbsolutePath());
}
4.ServletContextResource
// 注:要在Web环境中使用
@Test
public void testServletContextResource(){
// 路径开头的斜线代表当前Web应用的根目录
String path = "/WEB-INF/classes/applicationContext.xml";
Resource resource = new ServletContextResource(servletContext, path);
System.out.println(resource.getFile().getAbsolutePath());
}
使用特定格式的字符串表示各种类型的Resource
Prefix | Example | Explanation |
classpath: | classpath:com/winner/config.xml | load from the classpath |
file: | file:/data/config.xml | load from the filesystem |
http: | http://myserver/logo.jpg | load as a url |
(none) | /data/config.xml | it depends |
ApplicationContext ac = new ClassPathXmlApplicationContext(new String[] {//
"com/winner/spring/applicationContext_service.xml",//
"com/winner/spring/applicationContext_dao.xml" }); ApplicationContext ac2 = new ClassPathXmlApplicationContext(new String[] {//
"applicationContext_dao.xml", "applicationContext_service.xml" }, this.getClass());