Spring IOC容器的初始化過程--資源定位

      IOC容器的初始化是又refresh()方法啓動的,這個方法標誌着IOC容器的正式啓動。具體來說,這個啓動包括bean的resource定位,載入和註冊三個過程。今天我們主要了解資源定位的過程。

定位

       以編程的方式使用DefaultListableBeanFactory時,首先定義一個Resource來定位容器使用的BeanDefinition。這時使用的是ClassPathResource,這意味着Spring會在類路徑中去尋找以文件形式存在的BeanDefinition信息。
  1. ClassPathResource res=new ClassPathResource("beans.xml");
       這裏定義的Resource並不能由DefaultListableBeanFactory直接使用,Spring通過BeanDefinitionReader來對這些信息進行處理。我們也可以看到使用Application­Context 相對於直接使用DefaultListableBeanFactory的好處。因爲在ApplicationContext中,spring已經爲我們提供了一系列加載不同Resource的讀取器的實現,而DefaultListableBeanFactory只是一個純粹的IoC容器,需要爲它配置特定的讀取器才能完成這些功能。
        當然, 有利就有弊, 使用DefaultListableBeanFactory這種更底層的容器,能提高定製IoC容器的靈活性。
        FilesystemXmlApplicationContext可以從文件系統載入Resource,ClassPathXmlApplication­Context可以從ClassPath載入Resource,,XmlWebApplicationContext可以在Web容器中載入Resource。
       以FileSystemXmlApplicationContext爲例, 通過分析這個ApplicationContext的實現來看看它是怎樣完成這個Resource定位過程的。下面是這個ApplicationContext的繼承體系。

圖1   FilesystemXmlApplicationContext的繼承體系

從源代碼角度看:


                                          圖2    代碼角度看FilesystemXmlApplicationContext的繼承體系

FilesystemXmlApplicationContext.class

  1. public class FileSystemXmlApplicationContext extends AbstractXmlApplicationContext {
  2. public FileSystemXmlApplicationContext() {
  3. }
  4. public FileSystemXmlApplicationContext(ApplicationContext parent) {
  5. super(parent);
  6. }
  7. /**
  8. * Create a new FileSystemXmlApplicationContext, loading the definitions
  9. * from the given XML file and automatically refreshing the context.
  10. * @param configLocation file path
  11. * @throws BeansException if context creation failed
  12. */
  13. public FileSystemXmlApplicationContext(String configLocation) throws BeansException {
  14. this(new String[] {configLocation}, true, null);
  15. }
  16. /**
  17. * Create a new FileSystemXmlApplicationContext, loading the definitions
  18. * from the given XML files and automatically refreshing the context.
  19. * @param configLocations array of file paths
  20. * @throws BeansException if context creation failed
  21. */
  22. public FileSystemXmlApplicationContext(String... configLocations) throws BeansException {
  23. this(configLocations, true, null);
  24. }
  25. /**
  26. * Create a new FileSystemXmlApplicationContext with the given parent,
  27. * loading the definitions from the given XML files and automatically
  28. * refreshing the context.
  29. * @param configLocations array of file paths
  30. * @param parent the parent context
  31. * @throws BeansException if context creation failed
  32. */
  33. public FileSystemXmlApplicationContext(String[] configLocations, ApplicationContext parent) throws BeansException {
  34. this(configLocations, true, parent);
  35. }
  36. /**
  37. * Create a new FileSystemXmlApplicationContext, loading the definitions
  38. * from the given XML files.
  39. * @param configLocations array of file paths
  40. * @param refresh whether to automatically refresh the context,
  41. * loading all bean definitions and creating all singletons.
  42. * Alternatively, call refresh manually after further configuring the context.
  43. * @throws BeansException if context creation failed
  44. * @see #refresh()
  45. */
  46. public FileSystemXmlApplicationContext(String[] configLocations, boolean refresh) throws BeansException {
  47. this(configLocations, refresh, null);
  48. }
  49. /**
  50. * Create a new FileSystemXmlApplicationContext with the given parent,
  51. * loading the definitions from the given XML files.
  52. * @param configLocations array of file paths
  53. * @param refresh whether to automatically refresh the context,
  54. * loading all bean definitions and creating all singletons.
  55. * Alternatively, call refresh manually after further configuring the context.
  56. * @param parent the parent context
  57. * @throws BeansException if context creation failed
  58. * @see #refresh()
  59. */
  60. public FileSystemXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
  61. throws BeansException {
  62. super(parent);
  63. setConfigLocations(configLocations);
  64. if (refresh) {
  65. refresh();
  66. }
  67. }
  68. /**
  69. * Resolve resource paths as file system paths.
  70. * <p>Note: Even if a given path starts with a slash, it will get
  71. * interpreted as relative to the current VM working directory.
  72. * This is consistent with the semantics in a Servlet container.
  73. * @param path path to the resource
  74. * @return Resource handle
  75. * @see org.springframework.web.context.support.XmlWebApplicationContext#getResourceByPath
  76. */
  77. @Override
  78. protected Resource getResourceByPath(String path) {
  79. if (path != null && path.startsWith("/")) {
  80. path = path.substring(1);
  81. }
  82. return new FileSystemResource(path);
  83. }
  84. }
       我們可以看到在構造函數中,實現了對configuration進行處理的功能。讓所有配置在文件系統中的,以.XML 文件方式存在的BeanDefnition都能夠得到有效的處理。實現了 getResourceByPath方法,這個方法是個模板方法,是爲讀取Resource服務的。對於IoC容器功能的實現,這裏沒有涉及,因爲它繼承了AbstractXmlApplicationContext 。關於IoC容器功能相關的實現,都是在FileSysternXmlApplicationContext中完成的,但是在構造函數中通過refresh來啓動IoC容器的初始化,這個refresh方法非常重要,也是我們以後分析容器初始化過程實現的一個重要入口。
       關於讀入器的配置,可以到它的基類AbstractXmlApplicationContext中查看。
      
                                                           圖3   getResourceByPath的調用關係


                                                 圖4   getResourceByPath的調用過程
我們重點AbstractRefreshableApplicationContext的refreshBeanFactory方法的實現。

AbstractRefreshableApplicationContext.class

  1. protected final void refreshBeanFactory() throws BeansException {
  2. //這裏判斷,如果已經建立了BeanFactory,則銷燬並關閉該工廠。
  3. if (hasBeanFactory()) {
  4. destroyBeans();
  5. closeBeanFactory();
  6. }
  7. //創建並設置持有的DefaultListableBeanFactory的地方同時調用loadBeanDefinitions載入beandefinition信息
  8. try {
  9. DefaultListableBeanFactory beanFactory = createBeanFactory();
  10. beanFactory.setSerializationId(getId());
  11. customizeBeanFactory(beanFactory);
  12. loadBeanDefinitions(beanFactory);
  13. synchronized (this.beanFactoryMonitor) {
  14. this.beanFactory = beanFactory;
  15. }
  16. }
  17. catch (IOException ex) {
  18. throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
  19. }
  20. }
  21. //在上下文中創建DefaultListableBeanFactory的地方載入bean定義,因爲允許有多種載入方式,雖然用得最多的是XML定義的形式,
  22. //這裏通過一個抽象函數把具體的實現委託給子類來完成
  23. protected abstract void loadBeanDefinitions(DefaultListableBeanFactory beanFactory)
  24. throws BeansException, IOException;

AbstractBeanDefinitionReader.class

  1. public int loadBeanDefinitions(String location, Set<Resource> actualResources) throws BeanDefinitionStoreException {
  2. //這裏取得ResourceLoader,使用的是DefaultResourceLoader
  3. ResourceLoader resourceLoader = getResourceLoader();
  4. if (resourceLoader == null) {
  5. throw new BeanDefinitionStoreException(
  6. "Cannot import bean definitions from location [" + location + "]: no ResourceLoader available");
  7. }
  8. //對Resource的路徑模式進行解析,得到需要的Resource集合
  9. if (resourceLoader instanceof ResourcePatternResolver) {
  10. // Resource pattern matching available.
  11. try {
  12. Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
  13. int loadCount = loadBeanDefinitions(resources);
  14. if (actualResources != null) {
  15. for (Resource resource : resources) {
  16. actualResources.add(resource);
  17. }
  18. }
  19. if (logger.isDebugEnabled()) {
  20. logger.debug("Loaded " + loadCount + " bean definitions from location pattern [" + location + "]");
  21. }
  22. return loadCount;
  23. }
  24. catch (IOException ex) {
  25. throw new BeanDefinitionStoreException(
  26. "Could not resolve bean definition resource pattern [" + location + "]", ex);
  27. }
  28. }
  29. else {
  30. // Can only load single resources by absolute URL.
  31. Resource resource = resourceLoader.getResource(location);
  32. int loadCount = loadBeanDefinitions(resource);
  33. if (actualResources != null) {
  34. actualResources.add(resource);
  35. }
  36. if (logger.isDebugEnabled()) {
  37. logger.debug("Loaded " + loadCount + " bean definitions from location [" + location + "]");
  38. }
  39. return loadCount;
  40. }
  41. }

DefaultResourceLoader.class

  1. //對於取得Resource的具體過程,看DefaultResourceLoader是怎樣完成的。
  2. public Resource getResource(String location) {
  3. Assert.notNull(location, "Location must not be null");
  4. //這裏處理帶有classpath標識的Resource
  5. if (location.startsWith("/")) {
  6. return getResourceByPath(location);
  7. }
  8. else if (location.startsWith(CLASSPATH_URL_PREFIX)) {
  9. return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
  10. }
  11. else {
  12. try {
  13. //這裏處理帶有URL標識的Resource
  14. URL url = new URL(location);
  15. return new UrlResource(url);
  16. }
  17. catch (MalformedURLException ex) {
  18. // No URL -> resolve as resource path.
  19. //兩者都不是,用此方法,默認得到一個ClassPathContextResource,這個方法常用子類來實現
  20. //前面看到子類FilesystemXmlApplicationContext實現此方法,返回一個Filesystemresource。
  21. return getResourceByPath(location);
  22. }
  23. }
  24. }
        
         其他ApplicationContext會對應生成其他種類的Resource。下圖中我們可以看到Resource類的繼承關係。

 
                                                圖5   Resource的定義和繼承關係
       
       我們通過對FilesystemXmlApplicationContext的實現原理爲例,瞭解了Resource定位問題的解決方案。定位完成,接下來就是對返回的Resource對象進行載入了。接下來我們會介紹BeanDdfinition的載入和解析過程。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章