`
游伯度
  • 浏览: 21917 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

Spring IOC - 资源

阅读更多

通过上次Factory中分享,我们使用 FileSystemXmlApplicationContext 举例,其中赋予Application具体加载资源的功能,是因为大部分 ApplicationContext 都继承了 AbstractApplicationContext,而 AbstractApplicationContext 继承实现了 DefaultResourceLoader DefaultResourceLoader 中包含了加载资源的功能方法。

 

下面就从 DefaultResourceLoader 的源码入手,看看其是如何支持扩展的:

public class DefaultResourceLoader implements ResourceLoader {

	private ClassLoader classLoader;

	/**
	 * 创建默认的资源加载器。其中 ClassLoader 默认是当前线程的ContextClassLaoder。
	 * @see java.lang.Thread#getContextClassLoader()
	 */
	public DefaultResourceLoader() {
		this.classLoader = ClassUtils.getDefaultClassLoader();
	}

	/**
	 * 创建默认的资源加载器。 其中 ClassLoader 被指定。
	 */
	public DefaultResourceLoader(ClassLoader classLoader) {
		this.classLoader = classLoader;
	}

	public void setClassLoader(ClassLoader classLoader) {
		this.classLoader = classLoader;
	}

	public ClassLoader getClassLoader() {
		return (this.classLoader != null ? this.classLoader : ClassUtils.getDefaultClassLoader());
	}

	// 核心方法,获取资源。
	// 如果是用“classpath:”开头的资源返回 ClassPathResource,其他情况返回URL资源。
	// 如果URL资源创建失败,交给 getResourceByPath 方法供子类扩展。
	public Resource getResource(String location) {
		Assert.notNull(location, "Location must not be null");
		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 url = new URL(location);
				return new UrlResource(url);
			}
			catch (MalformedURLException ex) {
				// No URL -> resolve as resource path.
				// 子类可以扩展这个方法进行资源获取的扩展
				return getResourceByPath(location);
			}
		}
	}

	/**
	 * 通过指定的路径获取资源。
	 * 默认实现是使用类路径资源(ClassPathContextResource) 。
	 * 子类可以选择扩展这个方法达到新的资源加载的目的, 例如实现Servlet容器的资源加载。
	 * @param path the path to the resource
	 * @return the corresponding Resource handle
	 * @see ClassPathResource
	 * @see org.springframework.context.support.FileSystemXmlApplicationContext#getResourceByPath
	 * @see org.springframework.web.context.support.XmlWebApplicationContext#getResourceByPath
	 */
	protected Resource getResourceByPath(String path) {
		return new ClassPathContextResource(path, getClassLoader());
	}

	/**
	 * ClassPathContextResource 定义,继承了ClassPathResource,后面会相信说明这个类。
	 */
	private static class ClassPathContextResource extends ClassPathResource implements ContextResource {

		public ClassPathContextResource(String path, ClassLoader classLoader) {
			super(path, classLoader);
		}

		public String getPathWithinContext() {
			return getPath();
		}

		@Override
		public Resource createRelative(String relativePath) {
			String pathToUse = StringUtils.applyRelativePath(getPath(), relativePath);
			return new ClassPathContextResource(pathToUse, getClassLoader());
		}
	}
}

通过上面代码,我们可以出子类主要是通过 getResourceByPath(String)方法来实现自己的资源类型。默认支持的资源加载类型是类加载资源和URL资源。在上篇文章的分享中的 FileSystemXmlAppplicationContext 中就扩展了这个方法来支持文件方式(FileSystemResource)的加载资源文件。

 

下面在说说Spring中资源定义的体系。

Spring 是把所有的资源,包含类路径的、文件的、URL的等等都抽象成为 Resource 接口。关键接口的定义,可以查看 Spring的源码或G一下,网上有很多的介绍。我整理了一下他们类图,可以有个整体的认识,如下

资源体系类结构

 

上图灰色的是内部类,但是他们都是我们常用的 ResourceLoader 中定义的。例如 ClassPathContextResource 是定义在 DefaultResourceLoader 中,FileSystemContextResource 定义在 FileSystemResourceLoader中。关于 BeanDefinitionResource,他是一个内部的 Resource,具体的使用方式在后期的分享中会详细的讨论到。

重点介绍几个Resource

 

  • FileSystemResource

继承AbstractResource同时实现了WritableResourceFileSystemResource 是需要指定一个文件,无论是java.io.File 还是文件路径,他都需要具体的文件存在。同时,其还实现了 WritableResource 来支持文件的写入操作。

 

下面的代码是 FileSystemResource 的具体实现:

/**
 * This implementation opens a FileInputStream for the underlying file.
 * @see java.io.FileInputStream
 */
public InputStream getInputStream() throws IOException {
	return new FileInputStream(this.file);
}

/**
 * This implementation returns a URL for the underlying file.
 * @see java.io.File#toURI()
 */
@Override
public URL getURL() throws IOException {
	return this.file.toURI().toURL();
}

/**
 * This implementation returns a URI for the underlying file.
 * @see java.io.File#toURI()
 */
@Override
public URI getURI() throws IOException {
	return this.file.toURI();
}

/**
 * This implementation returns the underlying File reference.
 */
@Override
public File getFile() {
	return this.file;
}
/**
 * This implementation opens a FileOutputStream for the underlying file.
 * @see java.io.FileOutputStream
 */
public OutputStream getOutputStream() throws IOException {
	return new FileOutputStream(this.file);
}
 
  • ClassPathResource

ClassPathResource 重要的是使用 ClassLoader 来加载资源,至于 JVM ClassLoader 的具体原理读者可以G一下或者看看API文档。ClassLoader 默认是从ClassUtils.getDefaultClassLoader()获得。其首先通过当前线程中获取ContextClassLoader,如果获取不成功,使用 ClassUtils 类加载的 ClassLoader。当 ClassPathResource 没有指定 ClassLoader 或者指定的 ClassLoader null时,同时没有启动使用指定Class的关联加载时,上述默认策略将启动。使用指定的 Class 关联的 ClassLoader 进行加载,只需要在创建 ClassPathResouce 时,传入需要关联的 Class 即可。是由指定的 ClassLoader 加载还是指定的 Class 进行关联性的加载只能二者选择一种。

 

下面是 ClassPathResource 的关键实现代码:

/**
 * This implementation opens an InputStream for the given class path resource.
 * @see java.lang.ClassLoader#getResourceAsStream(String)
 * @see java.lang.Class#getResourceAsStream(String)
 */
public InputStream getInputStream() throws IOException {
	InputStream is;
	if (this.clazz != null) {
		is = this.clazz.getResourceAsStream(this.path);
	}
	else {
		is = this.classLoader.getResourceAsStream(this.path);
	}
	if (is == null) {
		throw new FileNotFoundException(getDescription() + " cannot be opened because it does not exist");
	}
	return is;
}

/**
 * This implementation returns a URL for the underlying class path resource.
 * @see java.lang.ClassLoader#getResource(String)
 * @see java.lang.Class#getResource(String)
 */
@Override
public URL getURL() throws IOException {
	URL url;
	if (this.clazz != null) {
		url = this.clazz.getResource(this.path);
	}
	else {
		url = this.classLoader.getResource(this.path);
	}
	if (url == null) {
		throw new FileNotFoundException(getDescription() + " cannot be resolved to URL because it does not exist");
	}
	return url;
}

/**
 * This implementation creates a ClassPathResource, applying the given path
 * relative to the path of the underlying resource of this descriptor.
 * @see org.springframework.util.StringUtils#applyRelativePath(String, String)
 */
@Override
public Resource createRelative(String relativePath) {
	String pathToUse = StringUtils.applyRelativePath(this.path, relativePath);
	return new ClassPathResource(pathToUse, this.classLoader, this.clazz);

}
 
  • ServletContextResource

ServletContextResource 需要使用到javax.servlet.ServletContext,其中 getURL getPathgetInputStream 实现直接使用 ServletContext 提供的相关实现进行转换。

/**
 * This implementation delegates to <code>ServletContext.getResourceAsStream</code>,
 * but throws a FileNotFoundException if no resource found.
 * @see javax.servlet.ServletContext#getResourceAsStream(String)
 */
public InputStream getInputStream() throws IOException {
	InputStream is = this.servletContext.getResourceAsStream(this.path);
	if (is == null) {
		throw new FileNotFoundException("Could not open " + getDescription());
	}
	return is;
}

/**
 * This implementation delegates to <code>ServletContext.getResource</code>,
 * but throws a FileNotFoundException if no resource found.
 * @see javax.servlet.ServletContext#getResource(String)
 */
@Override
public URL getURL() throws IOException {
	URL url = this.servletContext.getResource(this.path);
	if (url == null) {
		throw new FileNotFoundException(
				getDescription() + " cannot be resolved to URL because it does not exist");
	}
	return url;
}

/**
 * This implementation resolves "file:" URLs or alternatively delegates to
 * <code>ServletContext.getRealPath</code>, throwing a FileNotFoundException
 * if not found or not resolvable.
 * @see javax.servlet.ServletContext#getResource(String)
 * @see javax.servlet.ServletContext#getRealPath(String)
 */
@Override
public File getFile() throws IOException {
	URL url = this.servletContext.getResource(this.path);
	if (url != null && ResourceUtils.isFileURL(url)) {
		// Proceed with file system resolution...
		return super.getFile();
	}
	else {
		String realPath = WebUtils.getRealPath(this.servletContext, this.path);
		return new File(realPath);
	}
}

/**
 * This implementation creates a ServletContextResource, applying the given path
 * relative to the path of the underlying file of this resource descriptor.
 * @see org.springframework.util.StringUtils#applyRelativePath(String, String)
 */
@Override
public Resource createRelative(String relativePath) {
	String pathToUse = StringUtils.applyRelativePath(this.path, relativePath);
	return new ServletContextResource(this.servletContext, pathToUse);
}

 

  • 大小: 67.4 KB
分享到:
评论

相关推荐

    拓薪教育-Spring内幕深入剖析和实战精讲

    资源名称:拓薪教育-Spring内幕深入剖析和实战精讲资源目录:【】01.拓薪教育-spring3.2-序【】02.拓薪教育-Spring3.2-介绍IOC上【】03.拓薪教育-spring3.2-介绍IOC下【】04.拓薪教育-spring3.2-AOP和其他功能介绍...

    手写spring ioc(三) 资源org.zip

    本资源是个人手写spring ioc的源码,实现了ioc基本功能,解决了循环依赖,推动构造器,自动注入等

    Spring的IoC容器(《Spring揭秘》的精选版)

    迷你书是《Spring揭秘》的精选版,节选了原书中介绍Spring IoC容器的6个章节。《Spring揭秘》以幽默生动的语言、辅以有趣的故事和典故,循循善诱地阐述了Spring框架的方方面面。针对Spring框架的主要功能以及开发者...

    SpringSecurity.zip

    它提供了一组可以在Spring应用上下文中配置的Bean,充分利用了Spring IoC,DI(控制反转Inversion of Control ,DI:Dependency Injection 依赖注入)和AOP(面向切面编程)功能,为应用系统提供声明式的安全访问控制...

    IOC-死磕.xmind

    此资源对于想要观看spring源码的童鞋会很有帮助,但是要自己一步步跟代码才会有效果,另外关于ioc实现细节众多,这里只是提供一个整体的思路,要想完全吃透,必须得配合自己写的大量测试用例来跟代码

    Spring的IoC容器初始化源码解析

    Spring的IoC容器初始化源码解析,包括资源定位、加载、注册3个过程

    springIOC实例

    该资源包含了一个springIOC的简单实例代码,简单易懂。

    spring-framework-2.5.5和中文手册

    介绍了Spring2.5和拥有的新特性;主要讲述了核心技术:IOC、资源,校验、面向切面和测试用例;中间成数据访问:事务管理、DAO支出、JDBC进行数据访问和使用ORM工具进行数据访问;Web MVC 框架

    手写IOC项目,学习理解Spring IOC原理

    我们都知道,Spring框架的IOC是基于Java的反射机制实现,实现IOC,...IOC和DI是Spring里面最核心的东西,,资源中会写出这两个模块。资源内容包括Java反射机制的实践,使用反射机制实现IOC(包括依赖注入和对象创建)。

    java-spring教程-全面理解

    1、介绍了spring的概念 2、介绍了spring的控制反转IOC 3、介绍了spring的面向切面的编程AOP概念以及应用 4、介绍了spring的模板Template 5、spring与Struts的集成

    spring-01-ioc1.rar

    对应博客资源,免费下载

    Spring IOC AOP

    该资源包含了一些基本的spring IOC 和AOP的配置。利用ioc将程序进行解耦,将程序所依赖的组件放入spring容器中。动态注入给程序。

    02-spring-v1.zip

    手写spring IOC容器源码,作为博客《(一)手写spring IOC容器》的链接资源,是maven项目,

    spring框架约束步骤及教程

    Spring框架约束资源与步骤欢迎大家使用,Spring框架约束文件 sspring-core-4.1.6.RELEASE-sources.jar spring-core.jar 这个jar文件包含Spring框架基本的核心工具类,Spring其他组件都要使用到这个包里的类,是其他...

    Spring-Reference_zh_CN(Spring中文参考手册)

    6.8.3. 使用Spring IoC来配置AspectJ的切面 6.8.4. 在Spring应用中使用AspectJ Load-time weaving(LTW) 6.9. 其它资源 7. Spring AOP APIs 7.1. 简介 7.2. Spring中的切入点API 7.2.1. 概念 7.2.2. 切入点实施 ...

    SpringMVC精品资源--手写Spring,支持ioc(三级缓存)、aop(cglib)、内嵌tomcat.zip

    SpringMVC精品资源--手写Spring,支持ioc(三级缓存)、aop(cglib)、内嵌tomcat

    07-IoC配置-scope属性

    单例的对象是在加载spring容器时就创建了,且此后你在同一个bean获取资源时,用getBean()方法得到的对象都是同一个地址值的对象 prototype:,设定创建出的对象保存在spring容器中,是一个非单例的对象 非单例的...

    SSM框架的学习与应用-Java EE企业级应用开发学习记录-(第六天)初识Spring框架

    本资源是一篇关于学习和应用SSM框架(Spring、SpringMVC、MyBatis)的学习记录系列文章中的第六天内容,主题为初识Spring框架。 在这一部分中,你将了解到Spring框架的基本概念和使用方法,并通过实例探讨了Spring ...

    登陆案例jar包

    //包含访问配置文件、创建和管理bean 以及进行Inversion of Control / Dependency Injection(IoC/DI)操作相关的所有类。 spring-core-4.2.4.RELEASE.jar //这个jar 文件包含Spring 框架基本的核心工具类。Spring ...

    编程语言+JAVAspring+IoC容器+依赖注入

    编程语言+JAVAspring+IoC容器+依赖注入**:这是一个关于JAVAspring编程语言的IoC容器的依赖注入的资源,适合有一定JAVAspring基础的开发者。它介绍了JAVAspring的IoC容器的概念、原理和作用,以及如何使用JAVAspring...

Global site tag (gtag.js) - Google Analytics