1、XmlBeanFactory 的使用,参考MyEclipse Spring 学习总结一 Spring IOC容器

  1. public static void main(String[] args) {
  2. XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
  3. HelloWorld obj = (HelloWorld)factory.getBean("helloWorld");
  4. obj.getMessage();
  5.  
  6. }

  

2、使用DefaultListableBeanFactory和XmlBeanDefinitionReader

ClassPathResource resource = new ClassPathSource("beans.xml");

DefaultListableBeanFactory factory = new DefaultListableBeanFactory();

XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);

reader.loadBeanDefinitions(resource);

Spring加载资源并装配对象的过程

1、定义好Spring的配置文件

2、通过Resource将Spring配置文件进行抽象,抽象成一个Resource对象

3、定义好Bean工厂(各种BeanFactory)

4、定义好XmlBeanDefinitionReader对象,并将工厂对象作为参数传递进去供后续回调使用。

5、通过XmlBeanDefinitionReader对象读取之前抽象出的Resource对象(包含了XML文件的解析过程)

6、本质上,XML文件的解析是有XmlBeanDefinitionReader对象交由BeanDefinitionParserDelegate委托来完成的。实质上这里使用到类委托模式。

7、Ioc容器创建完毕,用户可以通过容器获取所需的对象信息。

3、查看ClassPathResource 

首先查看InputStreamSource接口,里面定义了一个getInputStream方法

  1. public interface InputStreamSource {
  2.  
  3. /**
  4. * Return an {@link InputStream}.
  5. * <p>It is expected that each call creates a <i>fresh</i> stream.
  6. * <p>This requirement is particularly important when you consider an API such
  7. * as JavaMail, which needs to be able to read the stream multiple times when
  8. * creating mail attachments. For such a use case, it is <i>required</i>
  9. * that each <code>getInputStream()</code> call returns a fresh stream.
  10. * @throws IOException if the stream could not be opened
  11. * @see org.springframework.mail.javamail.MimeMessageHelper#addAttachment(String, InputStreamSource)
  12. */
  13. InputStream getInputStream() throws IOException;
  14.  
  15. }

  

然后查看Resource接口

  1. public interface Resource extends InputStreamSource {
  2.  
  3. /**
  4. * Return whether this resource actually exists in physical form.
  5. * <p>This method performs a definitive existence check, whereas the
  6. * existence of a <code>Resource</code> handle only guarantees a
  7. * valid descriptor handle.
  8. */
  9. boolean exists();
  10.  
  11. /**
  12. * Return whether the contents of this resource can be read,
  13. * e.g. via {@link #getInputStream()} or {@link #getFile()}.
  14. * <p>Will be <code>true</code> for typical resource descriptors;
  15. * note that actual content reading may still fail when attempted.
  16. * However, a value of <code>false</code> is a definitive indication
  17. * that the resource content cannot be read.
  18. * @see #getInputStream()
  19. */
  20. boolean isReadable();
  21.  
  22. /**
  23. * Return whether this resource represents a handle with an open
  24. * stream. If true, the InputStream cannot be read multiple times,
  25. * and must be read and closed to avoid resource leaks.
  26. * <p>Will be <code>false</code> for typical resource descriptors.
  27. */
  28. boolean isOpen();
  29.  
  30. /**
  31. * Return a URL handle for this resource.
  32. * @throws IOException if the resource cannot be resolved as URL,
  33. * i.e. if the resource is not available as descriptor
  34. */
  35. URL getURL() throws IOException;
  36.  
  37. /**
  38. * Return a URI handle for this resource.
  39. * @throws IOException if the resource cannot be resolved as URI,
  40. * i.e. if the resource is not available as descriptor
  41. */
  42. URI getURI() throws IOException;
  43.  
  44. /**
  45. * Return a File handle for this resource.
  46. * @throws IOException if the resource cannot be resolved as absolute
  47. * file path, i.e. if the resource is not available in a file system
  48. */
  49. File getFile() throws IOException;
  50.  
  51. /**
  52. * Determine the content length for this resource.
  53. * @throws IOException if the resource cannot be resolved
  54. * (in the file system or as some other known physical resource type)
  55. */
  56. long contentLength() throws IOException;
  57.  
  58. /**
  59. * Determine the last-modified timestamp for this resource.
  60. * @throws IOException if the resource cannot be resolved
  61. * (in the file system or as some other known physical resource type)
  62. */
  63. long lastModified() throws IOException;
  64.  
  65. /**
  66. * Create a resource relative to this resource.
  67. * @param relativePath the relative path (relative to this resource)
  68. * @return the resource handle for the relative resource
  69. * @throws IOException if the relative resource cannot be determined
  70. */
  71. Resource createRelative(String relativePath) throws IOException;
  72.  
  73. /**
  74. * Determine a filename for this resource, i.e. typically the last
  75. * part of the path: for example, "myfile.txt".
  76. * <p>Returns <code>null</code> if this type of resource does not
  77. * have a filename.
  78. */
  79. String getFilename();
  80.  
  81. /**
  82. * Return a description for this resource,
  83. * to be used for error output when working with the resource.
  84. * <p>Implementations are also encouraged to return this value
  85. * from their <code>toString</code> method.
  86. * @see java.lang.Object#toString()
  87. */
  88. String getDescription();
  89.  
  90. /**
  91. * {@inheritDoc}
  92. * @return the input stream for the underlying resource (must not be {@code null}).
  93. */
  94. public InputStream getInputStream() throws IOException;
  95. }

  

4、ClassPathResource 源码

  1. public class ClassPathResource extends AbstractFileResolvingResource {
  2.  
  3. private final String path;
  4.  
  5. private ClassLoader classLoader;
  6.  
  7. private Class<?> clazz;
  8.  
  9. /**
  10. * Create a new ClassPathResource for ClassLoader usage.
  11. * A leading slash will be removed, as the ClassLoader
  12. * resource access methods will not accept it.
  13. * <p>The thread context class loader will be used for
  14. * loading the resource.
  15. * @param path the absolute path within the class path
  16. * @see java.lang.ClassLoader#getResourceAsStream(String)
  17. * @see org.springframework.util.ClassUtils#getDefaultClassLoader()
  18. */
  19. public ClassPathResource(String path) {
  20. this(path, (ClassLoader) null);
  21. }
  22.  
  23. /**
  24. * Create a new ClassPathResource for ClassLoader usage.
  25. * A leading slash will be removed, as the ClassLoader
  26. * resource access methods will not accept it.
  27. * @param path the absolute path within the classpath
  28. * @param classLoader the class loader to load the resource with,
  29. * or <code>null</code> for the thread context class loader
  30. * @see java.lang.ClassLoader#getResourceAsStream(String)
  31. */
  32. public ClassPathResource(String path, ClassLoader classLoader) {
  33. Assert.notNull(path, "Path must not be null");
  34. String pathToUse = StringUtils.cleanPath(path);
  35. if (pathToUse.startsWith("/")) {
  36. pathToUse = pathToUse.substring(1);
  37. }
  38. this.path = pathToUse;
  39. this.classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader());
  40. }
  41.  
  42. /**
  43. * Create a new ClassPathResource for Class usage.
  44. * The path can be relative to the given class,
  45. * or absolute within the classpath via a leading slash.
  46. * @param path relative or absolute path within the class path
  47. * @param clazz the class to load resources with
  48. * @see java.lang.Class#getResourceAsStream
  49. */
  50. public ClassPathResource(String path, Class<?> clazz) {
  51. Assert.notNull(path, "Path must not be null");
  52. this.path = StringUtils.cleanPath(path);
  53. this.clazz = clazz;
  54. }
  55.  
  56. /**
  57. * Create a new ClassPathResource with optional ClassLoader and Class.
  58. * Only for internal usage.
  59. * @param path relative or absolute path within the classpath
  60. * @param classLoader the class loader to load the resource with, if any
  61. * @param clazz the class to load resources with, if any
  62. */
  63. protected ClassPathResource(String path, ClassLoader classLoader, Class<?> clazz) {
  64. this.path = StringUtils.cleanPath(path);
  65. this.classLoader = classLoader;
  66. this.clazz = clazz;
  67. }
  68.  
  69. /**
  70. * Return the path for this resource (as resource path within the class path).
  71. */
  72. public final String getPath() {
  73. return this.path;
  74. }
  75.  
  76. /**
  77. * Return the ClassLoader that this resource will be obtained from.
  78. */
  79. public final ClassLoader getClassLoader() {
  80. return (this.classLoader != null ? this.classLoader : this.clazz.getClassLoader());
  81. }
  82.  
  83. /**
  84. * This implementation checks for the resolution of a resource URL.
  85. * @see java.lang.ClassLoader#getResource(String)
  86. * @see java.lang.Class#getResource(String)
  87. */
  88. @Override
  89. public boolean exists() {
  90. URL url;
  91. if (this.clazz != null) {
  92. url = this.clazz.getResource(this.path);
  93. }
  94. else {
  95. url = this.classLoader.getResource(this.path);
  96. }
  97. return (url != null);
  98. }
  99.  
  100. /**
  101. * This implementation opens an InputStream for the given class path resource.
  102. * @see java.lang.ClassLoader#getResourceAsStream(String)
  103. * @see java.lang.Class#getResourceAsStream(String)
  104. */
  105. public InputStream getInputStream() throws IOException {
  106. InputStream is;
  107. if (this.clazz != null) {
  108. is = this.clazz.getResourceAsStream(this.path);
  109. }
  110. else {
  111. is = this.classLoader.getResourceAsStream(this.path);
  112. }
  113. if (is == null) {
  114. throw new FileNotFoundException(getDescription() + " cannot be opened because it does not exist");
  115. }
  116. return is;
  117. }
  118.  
  119. /**
  120. * This implementation returns a URL for the underlying class path resource.
  121. * @see java.lang.ClassLoader#getResource(String)
  122. * @see java.lang.Class#getResource(String)
  123. */
  124. @Override
  125. public URL getURL() throws IOException {
  126. URL url;
  127. if (this.clazz != null) {
  128. url = this.clazz.getResource(this.path);
  129. }
  130. else {
  131. url = this.classLoader.getResource(this.path);
  132. }
  133. if (url == null) {
  134. throw new FileNotFoundException(getDescription() + " cannot be resolved to URL because it does not exist");
  135. }
  136. return url;
  137. }
  138.  
  139. /**
  140. * This implementation creates a ClassPathResource, applying the given path
  141. * relative to the path of the underlying resource of this descriptor.
  142. * @see org.springframework.util.StringUtils#applyRelativePath(String, String)
  143. */
  144. @Override
  145. public Resource createRelative(String relativePath) {
  146. String pathToUse = StringUtils.applyRelativePath(this.path, relativePath);
  147. return new ClassPathResource(pathToUse, this.classLoader, this.clazz);
  148. }
  149.  
  150. /**
  151. * This implementation returns the name of the file that this class path
  152. * resource refers to.
  153. * @see org.springframework.util.StringUtils#getFilename(String)
  154. */
  155. @Override
  156. public String getFilename() {
  157. return StringUtils.getFilename(this.path);
  158. }
  159.  
  160. /**
  161. * This implementation returns a description that includes the class path location.
  162. */
  163. public String getDescription() {
  164. StringBuilder builder = new StringBuilder("class path resource [");
  165.  
  166. String pathToUse = path;
  167.  
  168. if (this.clazz != null && !pathToUse.startsWith("/")) {
  169. builder.append(ClassUtils.classPackageAsResourcePath(this.clazz));
  170. builder.append('/');
  171. }
  172.  
  173. if (pathToUse.startsWith("/")) {
  174. pathToUse = pathToUse.substring(1);
  175. }
  176.  
  177. builder.append(pathToUse);
  178. builder.append(']');
  179. return builder.toString();
  180. }
  181.  
  182. /**
  183. * This implementation compares the underlying class path locations.
  184. */
  185. @Override
  186. public boolean equals(Object obj) {
  187. if (obj == this) {
  188. return true;
  189. }
  190. if (obj instanceof ClassPathResource) {
  191. ClassPathResource otherRes = (ClassPathResource) obj;
  192. return (this.path.equals(otherRes.path)
  193. && ObjectUtils.nullSafeEquals(this.classLoader, otherRes.classLoader) && ObjectUtils.nullSafeEquals(
  194. this.clazz, otherRes.clazz));
  195. }
  196. return false;
  197. }
  198.  
  199. /**
  200. * This implementation returns the hash code of the underlying
  201. * class path location.
  202. */
  203. @Override
  204. public int hashCode() {
  205. return this.path.hashCode();
  206. }
  207.  
  208. }

Spring源码之DefaultListableBeanFactory及资源载入的更多相关文章

  1. spring源码第一章_获取源码并将源码转为eclipse工程

    1.通过http://gitforwindows.org/下载github 2.通过http://services.gradle.org/distributions/下载gradle:gardle类似 ...

  2. Spring源码分析——资源访问利器Resource之实现类分析

    今天来分析Spring的资源接口Resource的各个实现类.关于它的接口和抽象类,参见上一篇博文——Spring源码分析——资源访问利器Resource之接口和抽象类分析 一.文件系统资源 File ...

  3. 【Spring 源码】Spring 加载资源并装配对象的过程(XmlBeanDefinitionReader)

    Spring 加载资源并装配对象过程 在Spring中对XML配置文件的解析从3.1版本开始不再推荐使用XmlBeanFactory而是使用XmlBeanDefinitionReader. Class ...

  4. Spring源码分析——资源访问利器Resource之接口和抽象类分析

    从今天开始,一步步走上源码分析的路.刚开始肯定要从简单着手.我们先从Java发展史上最强大的框架——Spring...旗下的资源抽象接口Resource开始吧. 我看了好多分析Spring源码的,每每 ...

  5. Spring源码学习-容器BeanFactory(一) BeanDefinition的创建-解析资源文件

    写在前面 从大四实习至今已一年有余,作为一个程序员,一直没有用心去记录自己工作中遇到的问题,甚是惭愧,打算从今日起开始养成写博客的习惯.作为一名java开发人员,Spring是永远绕不过的话题,它的设 ...

  6. Spring源码解读:核心类DefaultListableBeanFactory的继承体系

    1 简介 我们常用的ClassPathXmlApplicationContext是AbstractRefreshableApplicationContext的子类,而DefaultListableBe ...

  7. Spring 源码学习 04:初始化容器与 DefaultListableBeanFactory

    前言 在前一篇文章:创建 IoC 容器的几种方式中,介绍了四种方式,这里以 AnnotationConfigApplicationContext 为例,跟进代码,看看 IoC 的启动流程. 入口 从 ...

  8. 阅读spring源码

    读Spring源码之前,你要先清楚,为什么你要用Spring... Spring最基本的功能是做为管理bean的容器,所以我以为应该先从org.springframework.context包了解咯, ...

  9. [spring源码] 小白级别的源码解析ioc(二)

    之前一篇,整体描述了一下 Spring的整体概况和 jar包的介绍. 现在开始进入具体的源码解析,从本篇开始,先介绍spring的ioc容器.之前也看过一些介绍spring源码的, 有的是只讲整体的接 ...

随机推荐

  1. git 分支查看与切换

    git 分支查看与切换 # 1.查看所有分支 > git branch -a # 2.查看当前使用分支(结果列表中前面标*号的表示当前使用分支) > git branch # 3.切换分支 ...

  2. Android笔记(五十二) 侧滑菜单SlidingMenu

    SlidingMenu是一个优秀的开源项目,可以实现侧滑菜单,简单介绍一下这SlidingMenu的使用: 常用属性和方法: setTouchModeAbove(int i )是否可以通过滑动手势打开 ...

  3. php连接mySql,加密函数

    连接MySQL mysql_connect(servername,username,password); 面向对象: <?php $servername = "localhost&qu ...

  4. Java注解annotation : invalid type of annotation member

    前言 首先,关于注解的介绍就不多描述了,网上有很多这方面的资料.本文主要是介绍如何处理标题中遇到的问题:invalid type of annotation member ? 正文 Annotatio ...

  5. 适用于在线服务的A/B测试方法论

    适用于在线服务的A/B测试方法论 简介: 这篇文章旨在介绍适用于为在线服务进行A/B测试(A/B Test)的方法论.中文网络中目前还缺乏全面的入门级介绍. 我将首先讨论在线服务业进行A/B测试所考虑 ...

  6. window下关闭占用端口使用

    怎么在window下关闭端口! 1:查看特定端口被占用情况 命令:   netstat -ano 和 netstat -ano|findstr 端口号 netstat -ano:查看电脑所有端口被占用 ...

  7. 圆柱模板价格计算器V1.0版本

    因很多客户需求,就做了一个初始版本的产品圆柱模板面积和价格的计算器,界面非常简单,做工粗糙,但是功能是可以运行.后期会在界面和功能上进行升级,打算出一个微信小程序版本.这个程序仅供参考. 演示地址:h ...

  8. ado.net核心:DataTable对象

    概述 DataTable表示内存中数据的一个表. .net命名空间:System.Data DataTable构造方法 DataTable() //不带参数初始化DataTable 类的新实例. Da ...

  9. Vue 组件生命周期钩子

    Vue 组件生命周期钩子 # 1)一个组件从创建到销毁的整个过程,就称之为组件的生命周期 # 2)在组件创建到销毁的过程中,会出现众多关键的时间节点, 如: 组件要创建了.组件创建完毕了.组件数据渲染 ...

  10. NOI.ac 模拟赛20181103 排队 翘课 运气大战

    题解 排队 20% 1≤n≤20,1≤x,hi≤201\le n\le 20, 1\le x,h_i\le 201≤n≤20,1≤x,hi​≤20 随便暴力 50% 1≤n≤2000,1≤x,hi≤1 ...