zoukankan      html  css  js  c++  java
  • Spring 资源加载

    pom.xml
      <dependencies>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-core</artifactId>
          <version>4.3.14.RELEASE</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-beans</artifactId>
          <version>4.3.16.RELEASE</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>4.3.16.RELEASE</version>
        </dependency>
      </dependencies>
    

    Resource接口

    JDK没有提供从Web容器上下文及classpath中获取资源的操作类。鉴于此,spring设计了Resource接口,并使用策略模式提供了一些实现类。其实现类ServletContextResource从Web应用根目录下访问资源、ClassPathResource从类路径下访问资源、FileSystemResource从文件系统路径下访问资源。

        public static void main(String[] args) throws IOException {
            ClassPathResource resource1 = new ClassPathResource("config/my.xml");
            File file = resource1.getFile();
            /**
             * 如果资源文件在jar包中,因为jar本来就是一个文件,
             * 所以不能使用Resource.getFile()获取文件中的文件,
             * 可以使用Resource.getInputStream()获取jar中的文件
             */
            InputStream inputStream1 = resource1.getInputStream();
        }
    

    ResourceLoader接口

    ResourceLoader也使用了策略模式,该接口的实现类FileSystemXmlApplicationContext只能从文件系统下获取资源,但地址前缀可以省略;
    ClassPathXmlApplicationContext只能从类路径下获取资源,地址前缀也可以省略;PathMatchingResourcePatternResolver通过传入不同的地址前缀,自动选择相应的Resource实现类,前缀可以是classpath:,也可以是file:;Spring和SpringMVC也和PathMatchingResourcePatternResolver相同,既可以配置classpath:,也可以配置file:。

        public static void main(String[] args) throws IOException {
            ResourcePatternResolver resourceLoader = new PathMatchingResourcePatternResolver();
            Resource[] resources = resourceLoader.getResources("classpath*:*.xml");
            if (resources != null) {
                for (int i = 0; i < resources.length; i++) {
                  System.out.println(resources[i].getFilename());
                }
            }
        }
    
    • 资源地址可以使用的前缀有:1. classpath: 2. classpath*: 3.file: 4.http:// 5.ftp:// 6.没有前缀
    • 资源地址支持三种通配符:?匹配文件名中的一个字符;* 匹配文件名中任意字符;** 匹配多层路径
  • 相关阅读:
    【linux】linux根文件系统制作
    【linux】UBUNTU 12.04下傻瓜式简单安装arm-linux-gcc等gnu arm toolchain交叉编译工具
    【linux】内核编译
    【linux】内核源代码下载与阅读
    Jmeter实践
    常用sql 2018.08.31
    接口用例、实践参考
    UTF自动化测试工具
    MySql 中IFNULL、ISNULL、NULLIF用法(数据库判空)
    Mysql中FIND_IN_SET()和IN区别简析
  • 原文地址:https://www.cnblogs.com/Mike_Chang/p/10815752.html
Copyright © 2011-2022 走看看