spring ioc實現原理
一、一個普通的調用
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); GsonFormatBean bean = (GsonFormatBean) context.getBean("GsonFormatBean"); bean.isPalindrome(100);
1.1 分析第一步java
建立一個classPathXmlApplication的context,主要的實如今abstractAppplicationContext的refresh()這個方法中spring
@Override public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { // Prepare this context for refreshing. prepareRefresh(); // Tell the subclass to refresh the internal bean factory. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); // Prepare the bean factory for use in this context. prepareBeanFactory(beanFactory); try { // Allows post-processing of the bean factory in context subclasses. postProcessBeanFactory(beanFactory); // Invoke factory processors registered as beans in the context. invokeBeanFactoryPostProcessors(beanFactory); // Register bean processors that intercept bean creation. registerBeanPostProcessors(beanFactory); // Initialize message source for this context. initMessageSource(); // Initialize event multicaster for this context. initApplicationEventMulticaster(); // Initialize other special beans in specific context subclasses. onRefresh(); // Check for listener beans and register them. registerListeners(); // Instantiate all remaining (non-lazy-init) singletons. finishBeanFactoryInitialization(beanFactory); // Last step: publish corresponding event. finishRefresh(); } catch (BeansException ex) { if (logger.isWarnEnabled()) { logger.warn("Exception encountered during context initialization - " + "cancelling refresh attempt: " + ex); } // Destroy already created singletons to avoid dangling resources. destroyBeans(); // Reset 'active' flag. cancelRefresh(ex); // Propagate exception to caller. throw ex; } finally { // Reset common introspection caches in Spring's core, since we // might not ever need metadata for singleton beans anymore... resetCommonCaches(); } } }
使用對象鎖保證只有一個線程訪問邏輯app
第一步:ide
設置容器的一些全局性參數,好比closed,active等參數post
第二步:this
告訴父類建立一個bean工廠spa
刷新整個bean工廠,獲取一個ConfigurableListableBeanFacotory,返回bean工廠。線程
刷新beanFactorycode
建立一個DefaultListableBeanFactory,設置一些屬性,加載beanDefinition,具體的實如今abstractxmlApplicationContext、AnnotationWebConfigApplicationContext等orm
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
容器怎麼實現加載全部的bean
兩個關鍵的方法:
容器註冊全部的beanDefinitions
解析單個bean的操做
最終生成beanDefination,也就是將xml映射成爲一個bean
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------