Spring源码-浅识ResourceLoader

发布时间:2023-05-21 09:17:10

在使用spring框架时,以xml文件的形式存在于系统路径中。启动spring时,首先加载资源文件。在spring中加载资源文件主要由resourceloader完成

只有Defaultresourceloder才能直接实现Resourceloader

Spring源码-浅识ResourceLoader_spring

获取资源的具体方法

@Overridepublic Resource getResource(String location) {// 判断资源路径文件是否存在Assertt.notNull(location, "Location must not be null");// 未来扩展功能 在 5.0.2版本没有实现for (ProtocolResolver protocolResolver : this.protocolResolvers) {Resource resource = protocolResolver.resolve(location, this);if (resource != null) {return resource;}}//如果是类路径的方式,那需要使用 ClassPathResource 得到bean if是文件的资源对象 (location.startsWith(/) {return getResourceByPath(location);} else if (location.startsWith(CLASSPATH_URL_PREFIX)) {return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());}else {try {// Try to parse the location as a URL...// 假如是URL 方式,使用Urlresource使用Urlesource 作为bean URLL url = new URL(location);return (ResourceUtils.isFileURL(url) ? new FileUrlResource(url) : new UrlResource(url));}catch (MalformedURLException ex) {// No URL -> resolve as resource path.//如果不是classpath标志,如果不是URL标志的Resource定位,则调用///容器本身的getresourceByPath获取Resourcereturn getResourceByPath(location);}}}

  • 如上所示,获取资源的方式有三种
  • 通过 getResourceByPath 分析资源路径 location
  • 通过 ClassPathResource 去获取
  • 通过 URL 远程获取
getResourceByPath

这种方法最终调用的是Claspathresource的结构方法

protected Resource getResourceByPath(String path) {    return new ClassPathContextResource(path, getClassLoader());}public ClassPathContextResource(String path, @Nullable ClassLoader classLoader) {    super(path, classLoader);}public ClassPathResource(String path, @Nullable ClassLoader classLoader) {    Assert.notNull(path, "Path must not be null");    String pathToUse = StringUtils.cleanPath(path);    if (pathToUse.startsWith(/) {        pathToUse = pathToUse.substring(1);    }    this.path = pathToUse;    this.classLoader = (classLoader != null ?= null ? classLoader : ClassUtils.getDefaultClassLoader());}

ClassPathResource

关注这里

/** * {@link Resource} implementation for class path resources. Uses either a * given {@link ClassLoader} or a given {@link Class} for loading resources. * * <p>Supports resolution as {@code java.io.File} if the class path * resource resides in the file system, but not for resources in a JAR. * Always supports resolution as URL. *///TODO  实现类路径资源,使用给定的clasloader或类加载资源


资源加载完成后,需要处理资源,或者换句话说,谁将开始加载资源?

defaultresourceloader的实现关系

Spring源码-浅识ResourceLoader_源码_02

defaultresourceloader具有处理资源的能力,因此继承defaultresourceloader的类别也具有处理资源的能力。因此,当我们使用spring时,启动spring的第一步是定位和加载资源Spring Web 项目为例,资源是指我们定义的applicationcontextext.xml web.xml

上一篇 过滤器和监听器
下一篇 WPF控件模板查看

文章素材均来源于网络,如有侵权,请联系管理员删除。

标签: Java教程Java基础Java编程技巧面试题Java面试题