Spring 资源加载

pom.xml ``` org.springframework spring-core 4.3.14.RELEASE org.springframework spring-beans 4.3.16.RELEASE org.springframework spring-context 4.3.16.RELEASE ```

Resource接口

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

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:。spa

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.没有前缀
  • 资源地址支持三种通配符:?匹配文件名中的一个字符;* 匹配文件名中任意字符;** 匹配多层路径
相关文章
相关标签/搜索