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()); } } }