Spring的Resource接口、ResourcesLoader接口使用了策略模式,Resources接口及其实现类是一个算法族,ResourcesLoader接口的实现类通过传入不同的参数自动调用算法族里的某个算法。
Resource接口简介:
JDK没有提供从Web容器上下文及classpath中获取资源的操作类。鉴于此,spring设计了Resource接口,该接口的实现类ServletContextResource从Web应用根目录下访问资源、ClassPathResource从类路径下访问资源。
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(); }