Spring中的Resource

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

PrefixExampleExplanation
classpath:classpath:com/winner/config.xmlload from the classpath
file:file:/data/config.xmlload from the filesystem
http:http://myserver/logo.jpgload as a url
(none)/data/config.xmlit 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());

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值