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也使用了策略模式,該接口的實現類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()); } } }