directory

  • 1. The basic
  • 2. Xml-based configuration of IOC
  • 3. Annotations based configuration of IOC
  • 4. Concepts related to AOP
  • 6. The spring into the order
  • 7. Message monitoring mechanism
  • 8. Behavior of things control and dissemination
  • 9. The Spring source code
  • 10. The Spring lifecycle

To edit

ClassPathXmlApplicationContext
    // Configure the core method of the container
    - refresh

refresh
    // To prepare, record the container startup time, set a startup flag state, and handle placeholders in the configuration file
    1prepareRefresh()
    	1.2this.startupDate = System.currentTimeMillis();
		1.3this.closed.set(false);
		1.4this.active.set(true);
	// Parse the configuration file into beanDefinitions. By registering this information to the BeanFactory, the bean is not initialized, it is only registered
	2.obtainFreshBeanFactory();
		// Close the old BeanFactory, create a new BeanFactory, load beanDefination, and register the bean
		2.1refreshBeanFactory()
            / / initialize a DefaultListableBeanFactory
            2.11. createBeanFactory();
      		// Set two configuration properties of BeanFactory: whether Bean overrides are allowed and whether circular references are allowed
            2.1.2customizeBeanFactory(beanFactory);
			 // Load the Bean into the BeanFactory
      		2.13. loadBeanDefinitions(beanFactory)
                // Instantiate an XmlBeanDefinitionReader for this BeanFactory
				2.13..1XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
				// Load the bean, using the initialized reader to load the XML configuration
				2.13.2. loadBeanDefinitions(beanDefinitionReader);
					// Core section, load bean
					2.13.2.1.return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
						// Returns the number of beans loaded by the current BeanFactory
						2.13.2.1..1registerBeanDefinition
                            // Convert the XML configuration file into a configuration tree
                            2.13.2.1.1..1Element root = doc.getDocumentElement();
							// Load beanDefination according to the configuration tree to complete the profile environment configuration
							2.13.2.1.1..2doRegisterBeanDefinitions(root);
								// Different tags are parsed, and different spaceHandlers are called for different tags
								2.13.2.1.1.2.1. parseBeanDefinitions(root, this.delegate);
									
      , 
      , 
      , 
      
									2.13.2.1.1.2.1..1parseDefaultElement(ele, delegate) 
                                        // Process the 
      
        tag
      
                                        2.13.2.1.1.2.1.1..1processBeanDefinition(ele, delegate);
											// Extract the information from the 
       node, then encapsulate it in a BeanDefinitionHolder to convert the bean tags in XML to BeanDefinition
   											2.13.2.1.1.2.1.1.1..1BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
											// Register the Bean with its name and alias as the key and beanDefinition as value, stored in the map
											2.13.2.1.1.2.1.1.1..1BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry())     
                                    // Parse < MVC />, 
      , 
      , 
      , etc
                                    2.13.2.1.1.2.1..1delegate.parseCustomElement(element) 
// Prepare the Bean container, add some BeanPostProcessors, register listeners, etc
3.prepareBeanFactory(factory)
   		// Set the BeanFactory classloader for the current ApplicationContext
        3.1setBeanClassLoader(getClassLoader)
       // Add a BeanPostProcessor, which is relatively simple
       This processor is responsible for the callback of the special Beans that implement the Aware interface when they are initialized
       3.2  beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));                                 
       // Some beans that implement a special interface are ignored during autowiring
       3.3 ignoreDependencyInterface
		// Inject values into beans that implement special interfaces
       3.4 registerResolvableDependency
 		// The BeanPostProcessor is also very simple. After the bean is instantiated, if it is a subclass of ApplicationListener,
   		// Register an event listener
       3.5beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
       // Manually register a few special beans


// This is the extension point provided to subclasses, at which point all beans have been loaded and registered, but have not been initialized
// Executes methods that implement the BeanFactoryPostProcessor interface class
4.postProcessBeanFactory(beanFactory);
// Call the postProcessBeanFactory(Factory) method of each BeanFactoryPostProcessor implementation class
5.invokeBeanFactoryPostProcessors(beanFactory);
 
// Register the BeanPostProcessor implementation class. Note the difference between BeanPostProcessor and BeanFactoryPostProcessor
/ / the interface of two methods: postProcessBeforeInitialization and postProcessAfterInitialization
// Two methods are executed before and after Bean initialization, respectively. Notice that the Bean is not initialized at this point
6.registerBeanPostProcessors(beanFactory);
 
// Initialize the MessageSource of the current ApplicationContext
7.initMessageSource();
 
// Initializes the event announcer for the current ApplicationContext
 8.initApplicationEventMulticaster();
 
// A typical template method (hook method),
// Specific subclasses can initialize special beans here (before initializing Singleton beans)
9.onRefresh();
 
// Register event listeners that implement the ApplicationListener interface. That's not what we're talking about. Go
10.registerListeners();
                        
// Initialize all Sigleton beans, and complete the instantiation of all beans at this stage
11. finishBeanFactoryInitialization   
    11.1// Initialize all conversionService beans that can be converted to the type
	// Initialize the remaining beans
   	 11.2  beanFactory.preInstantiateSingletons();
			// The for loop processes all singleton beans
 			for (String beanName : beanNames) {
				// Merge its parent attribute, involving the parent attribute
			 	11.2.1RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
				// Process the factoryBean
				11.12. if (isFactoryBean(beanName)
				For normal beans, just call getBean(beanName) to initialize them
            	11.23. getBean(beanName);
                      11.23.1. doGetBean
                      		// Handle aliases and factoryBeans
                      		11.23.1.1. transformedBeanName(name);
                            // Check if it has already been created
   							11.23.1.2. Object sharedInstance = getSingleton(beanName);
                           // If agRS is empty, you want to create beans, otherwise you want to get beans
							if(sharedInstance ! =null && args == null) {}else{
                                 	// Check if the BeanDefinition exists in the container
      								11.23.1..3BeanFactory parentBeanFactory = getParentBeanFactory();
                                	// Initialize all dependent beans first, which is easy to understand.
        					 		// Note that dependency refers to dependence as defined in Depends -on
         							 11.23.1..4String[] dependsOn = mbd.getDependsOn();
                               		 // Create an instance of singleton
                                	// Create an instance of singleton
                                    11.23.1.. 5
         							if (mbd.isSingleton()) {
                      						11.23.1.. 51. return createBean(beanName, mbd, args);
                                        	// Make sure the Class in BeanDefinition is loaded
   											11.23.1.. 52.Class<? > resolvedClass = resolveBeanClass(mbd, beanName);// Prepare method overwrite
                                        	11.23.1.. 53. mbdToUse.prepareMethodOverrides();
                                        	// Create BeanPostProcessor bean
                                        	11.23.1.. 54. Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
											/ / create a bean
                      						11.23.1.. 5. 5 Object beanInstance = doCreateBean(beanName, mbdToUse, args);
                      								// Instantiate the Bean
                      						 		11.23.1.. 5. 51. instanceWrapper = createBeanInstance(beanName, mbd, args);
                                        							// Call the factory method to instantiate the bean
                                        							 return instantiateUsingFactoryMethod(beanName, mbd, args);
																	// Dependency injection with a constructor
        															 return autowireConstructor(beanName, mbd, null.null);
                                        							// No argument constructor
         															return instantiateBean(beanName, mbd);
                                        								  	/ / instantiate
         																	beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
                                        											// If no method overrides exist, use Java reflection for instantiation, otherwise use CGLIB
                                        											// Instantiate using constructors
      																				return BeanUtils.instantiateClass(constructorToUse);
                                        											// Use CGLIB for instantiation
                                        											return instantiateWithMethodInjection(bd, beanName, owner);

                      								// Resolve loop dependencies
													 11.23.1.. 5. 52. boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&isSingletonCurrentlyInCreation(beanName)
                                              		// This step is also critical. This step is responsible for the attribute assembly, because the previous instance was instantiated without setting the value
    									     		11.23.1.. 5. 53. populateBean(beanName, mbd, instanceWrapper);
                                                                      // Find all attribute values by name. If it is a bean dependency, initialize the dependent bean first. Recording dependencies
     																 if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
         																	autowireByName(beanName, mbd, bw, newPvs);
     																}
																	// Assemble by type. complicated
      																if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
        																	 autowireByType(beanName, mbd, bw, newPvs);
      																}
                                                                    // Set the property value of the bean instance
   																	applyPropertyValues(beanName, mbd, bw, pvs);
                                             		 // Remember init-method? And the InitializingBean interface? And the BeanPostProcessor interface?
             								 		 // Handle the various callbacks after the bean is initialized
        									  		11.23.1.. 5. 54. exposedObject = initializeBean(beanName, exposedObject, mbd);
                                                                      // If the bean implements the BeanNameAware, BeanClassLoaderAware, or BeanFactoryAware interface, callback
     																 invokeAwareMethods(beanName, bean);
																	 / / BeanPostProcessor postProcessBeforeInitialization callback
     																 wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
																	 // Handle the init-method defined in the bean,
     																  // Or if the bean implements the InitializingBean interface, call the afterPropertiesSet() method
      																 invokeInitMethods(beanName, wrappedBean, mbd);
																	/ / BeanPostProcessor postProcessAfterInitialization callback
     																 wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);

                                    } // Create a prototype instance
       					 			 else if(mbd.isPrototype()) { prototypeInstance = createBean(beanName, mbd, args); }}Copy the code