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.沒有前綴
  • 資源地址支持三種通配符:?匹配文件名中的一個字符;* 匹配文件名中任意字符;** 匹配多層路徑
相關文章
相關標籤/搜索