美文网首页
Spring扩展(3)-资源加载

Spring扩展(3)-资源加载

作者: Terminalist | 来源:发表于2018-02-09 15:48 被阅读137次

1.Resource

Resource接口可以根据资源的不同类型,或者资源所处的不同场合,给出相应的具体实现;
Spring中提供了以下一些实现类:


image.png

Resource接口定义了11个方法,可以帮助我们查询资源状态、访问资源内容,甚至根据当前资源创建新的相对资源。不过,要真想实现自定义的Resource,倒是真没必要直接实现该接口,我们可以继承AbstractResource抽象类,然后根据当前具体资源特征,覆盖相应的方法就可以了。

2.ResourceLoader

  • ResourceLoader主要用来去查找和定位这些资源,其实就是主要通过Resource#getResource方法,通过它,我们就可以根据指定的资源位置,定位到具体的资源实例;
    ResourceLoader有一个默认的实现类,即DefaultResourceLoader,该类默认的资源查找处理逻辑如下,同时还有FileSystemResourceLoader,ClassRelativeResourceLoader,这些类的目的是为了扩展DefaultResourceLoader,处理一些DefaultResourceLoader处理不到的场景,当然,这样也给我们参考去实现自己特殊场景下自定义实现:
 public Resource getResource(String location) {
        Assert.notNull(location, "Location must not be null");
        for (ProtocolResolver protocolResolver : this.protocolResolvers) {
            Resource resource = protocolResolver.resolve(location, this);
            if (resource != null) {
                return resource;
            }
        }
        //1.判断是否以"/"打头,是则委派getResourceByPath(String)方法来定位
        if (location.startsWith("/")) {
            return getResourceByPath(location);
        }
        //2.检查资源路径是否以classpath:前缀打头,是则尝试构造ClassPathResource类 型资源并返回
        else if (location.startsWith(CLASSPATH_URL_PREFIX)) {
            return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
        }
        else {
            try {
                //3.通过URL资源路径来定位资源,如果没有抛出MalformedURLException, 有则会构造UrlResource类型的资源并返回
                URL url = new URL(location);
                return new UrlResource(url);
            }catch (MalformedURLException ex) {
                return getResourceByPath(location);
            }
        }
    }
  • 关于DefaultResourceLoader的使用
    借助其内部的getResource操作,我们可以这样做:
@Test
public void testResourceTypesWithFileSystemResourceLoader() {
    ResourceLoader resourceLoader = new FileSystemResourceLoader();
    Resource fileResource = resourceLoader.getResource(path);
    log.info("{}", fileResource instanceof FileSystemResource);
    log.info("{}", fileResource.exists());
    Resource urlResource = resourceLoader.getResource("file:" + path);
    log.info("{}", urlResource instanceof UrlResource);
}
  • ResourcePatternResolver(多个ResourceLoader)
    ResourcePatternResolver是ResourceLoader的扩展,ResourceLoader每次只能根据资源路径 返回确定的单个Resource实例,而ResourcePatternResolver则可以根据指定的资源路径匹配模式, 每次返回多个Resource实例;
public interface ResourcePatternResolver extends ResourceLoader {
    String CLASSPATH_ALL_URL_PREFIX = "classpath*:";
    Resource[] getResources(String var1) throws IOException;
}

ResourcePatternResolver在ResourceLoader原有定义的基础上,新增了getResources方法定义,以支持根据路径匹配模式返回多个Resources的功能。它同时还引入了一种新的协议前缀classpath*:,针对这一点的支持,将由相应的子类实现给出,这里我会分析PathMatchingResourcePatternResolver的相关实现;

 //1.构造函数可指定传入classLoader,作为resourceLoader的实现
 public PathMatchingResourcePatternResolver(ClassLoader classLoader) {
    this.resourceLoader = new DefaultResourceLoader(classLoader);
 }

 //2.支持Ant风格的路径匹配模式,
 private PathMatcher pathMatcher = new AntPathMatcher();
 public void setPathMatcher(PathMatcher pathMatcher) {
    Assert.notNull(pathMatcher, "PathMatcher must not be null");
    this.pathMatcher = pathMatcher;
 }

 //3.如果不符合ant风格的格式,其在加载资源的行为上会与DefaultResourceLoader基本相同, 只存在返回的Resource数量上不同;
 public Resource[] getResources(String locationPattern) throws IOException {
    Assert.notNull(locationPattern, "Location pattern must not be null");
    if (locationPattern.startsWith(CLASSPATH_ALL_URL_PREFIX)) {
        if (getPathMatcher().isPattern(locationPattern.substring(CLASSPATH_ALL_URL_PREFIX.length()))) {
            return findPathMatchingResources(locationPattern);
        }
        else {
            return findAllClassPathResources(locationPattern.substring(CLASSPATH_ALL_URL_PREFIX.length()));
        }
    }
    else {
        int prefixEnd = (locationPattern.startsWith("war:") ? locationPattern.indexOf("*/") + 1 :
                locationPattern.indexOf(":") + 1);
        if (getPathMatcher().isPattern(locationPattern.substring(prefixEnd))) {
            return findPathMatchingResources(locationPattern);
        }
        else {
            return new Resource[] {getResourceLoader().getResource(locationPattern)};
        }
    }
}

关于其使用,默认使用的是DefaultResourceLoader,但我们可以手动改变ResourceLoader:

@Test
public void testPathMatchingResourcePatternResolver() {
    ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
    Resource fileResource = resourceResolver.getResource(path);
    log.info("{}", fileResource instanceof ClassPathResource);
    log.info("{}", fileResource.exists());
    resourceResolver = new PathMatchingResourcePatternResolver(new FileSystemResourceLoader());
    fileResource = resourceResolver.getResource(path);
    log.info("{}", fileResource instanceof FileSystemResource);
    log.info("{}", fileResource.exists());
}

3.ApplicationContext

此时此刻,对Spring内部的资源加载应该已经很清晰了,但是你是否发现,在spring的内部,其实都是ApplicationContext这个东西在作怪哦!接下来,我将讲述下ApplicationContext是怎么做到资源统一加载的;

public interface ApplicationContext extends EnvironmentCapable, ListableBeanFactory, HierarchicalBeanFactory,MessageSource,ApplicationEventPublisher, ResourcePatternResolver{
        ....
} 

看类继承关系,你有没有看到ResourcePatternResolver,这个玩意就是ApplicationContext支持spring统一资源加载的真相;ApplicationContext实现类是AbstractApplicationContext,再看它的实现:

public abstract class AbstractApplicationContext extends DefaultResourceLoader
    implements ConfigurableApplicationContext, DisposableBean {

    /** ResourcePatternResolver used by this context */
    private ResourcePatternResolver resourcePatternResolver;

    public AbstractApplicationContext() {
        this.resourcePatternResolver = getResourcePatternResolver();
    }

    protected ResourcePatternResolver getResourcePatternResolver() {
        return new PathMatchingResourcePatternResolver(this);
    }
        ...
}

AbstractApplicationContext继承了DefaultResourceLoader,所以啊,它的getResource方法当然就直接用DefaultResourceLoader的了,而getResources则用的其内部声明的resourcePatternResolver,对应的实例类型为PathMatchingResourcePatternResolver,之前说过,PathMatchingResourcePatternResolver构造的时候会接受一个ResourceLoader,而AbstractApplicationContext本身又继承自DefaultResourceLoader,自然把this传入即可啦;
总结下:

  • ApplicationContext的实现类在作为ResourceLoader或者ResourcePatternResolver时候的行为,完全就是委派给了PathMatchingResourcePatternResolver和DefaultResourceLoader来做!
    所以,我们其实还可以这么使用:
@Test
public void testApplicationContext() {
    //以ResourceLoader的方式使用
    ResourceLoader resourceLoader = new ClassPathXmlApplicationContext(configurePath);
    // 或者
    //ResourceLoader resourceLoader = new FileSystemXmlApplicationContext(configurePath);
    Resource fileResource = resourceLoader.getResource(path);
    log.info("{}", fileResource instanceof ClassPathResource);
    log.info("{}", fileResource.exists());
    Resource urlResource2 = resourceLoader.getResource("http://www.spring21.cn");
    log.info("{}", urlResource2 instanceof UrlResource);
}
  • 那么关于ResourceLoader类型的注入,从前我们都是通过属性注入或者setter注入时是这么玩的;
public class FooBar{
    private ResourceLoader resourceLoader;

    public void foo(String location) {
      System.out.println(getResourceLoader().getResource(location).getClass());
    }

    public ResourceLoader getResourceLoader() { return resourceLoader;}

    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;   
    }
}

然后这么配置:

<bean id="resourceLoader" class="org.springframework.core.io.DefaultResourceLoader"> </bean>
<bean id="fooBar" class="...FooBar"> 
    <property name="resourceLoader">
        <ref bean="resourceLoader"/> 
    </property>
</bean>

然而ApplicationContext容器本身就是一个ResourceLoader,我们为了该类还需要单独提供一个resourceLoader实例就有些多于了,直接将当前的ApplicationContext容器作为ResourceLoader注入不就行了? 而ResourceLoaderAware和ApplicationContextAware接口都帮助我们做到这一点!这时候代码应该这么写了;

public class FooBar implements ResourceLoaderAware{
    private ResourceLoader resourceLoader;

    public void foo(String location){
        System.out.println(getResourceLoader().getResource(location).getClass());
    }

    public ResourceLoader getResourceLoader() {
        return resourceLoader;
    }

    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }
}

or 这么写:

public class FooBar implements ApplicationContextAware{
    private ResourceLoader resourceLoader;

    public void foo(String location){
        System.out.println(getResourceLoader().getResource(location).getClass());
    }

    public ResourceLoader getResourceLoader() {
        return resourceLoader;
    }

    public void setApplicationContext(ApplicationContext ctx) throws BeansException {
        this.resourceLoader = ctx;
    }
}

这时候的配置文件该这么描述,多么清爽啊!:

<bean id="fooBar" class="...FooBar" />

容器启动的时候,就会自动将当前ApplicationContext容器本身 注入到FooBar中,因为ApplicationContext类型容器可以自动识别Aware接口,

ok! 写了一大堆,应该描述清楚了吧,谨以此文献给最近悠闲的自己,多学习,多动手,多做总结!

相关文章

网友评论

      本文标题:Spring扩展(3)-资源加载

      本文链接:https://www.haomeiwen.com/subject/ogaftftx.html