zoukankan      html  css  js  c++  java
  • 策略模式应用

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

      ResourceLoader接口简介
      通过传入的地址前缀,自动选择Resource实现类。

        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());
                }
            }
        }
    View Code
    • 资源地址可以使用的前缀有:1. classpath: 2. classpath*: 3.file: 4.http:// 5.ftp:// 6.没有前缀
    • 资源地址支持三种通配符:?匹配文件名中的一个字符;* 匹配文件名中任意字符;** 匹配多层路径 3. ResourceLoader的实现类PathMatchingResourcePatternResolver
    public class PathMatchingResourcePatternResolver implements ResourcePatternResolver {}
    public interface ResourcePatternResolver extends ResourceLoader {
      // 根据classpath*:查询资源
      String CLASSPATH_ALL_URL_PREFIX = "classpath*:";
      // 支持通配符的资源路径表达式
      Resource[] getResources(String locationPattern) throws IOException;
    }
    public interface ResourceLoader {
      // 根据classpath:查询资源
      String CLASSPATH_URL_PREFIX = "classpath:";
      Resource getResource(String var1);
      ClassLoader getClassLoader();
    }
    View Code
  • 相关阅读:
    结对第二次作业——某次疫情统计可视化的实现
    结对第一次—疫情统计可视化(原型设计)
    个人作业——软件工程实践总结&个人技术博客
    虚拟列表(VirtualList)在Taro3中的使用
    结对第二次作业—某次疫情统计可视化的实现
    结对第一次—疫情统计可视化(原型设计)
    软工实践寒假作业(2/2)
    软工实践寒假作业(1/2)
    个人作业——软件工程实践总结&个人技术博客
    Spring Boot
  • 原文地址:https://www.cnblogs.com/Mike_Chang/p/11302519.html
Copyright © 2011-2022 走看看