General documentation: Article directory Github: github.com/black-ant

A. The preface

This article will look at the overall logic of ApplicationContext in detail. The most important part of the logic of ApplicationContext has the following functions:

  • The ability to access Bean factory methods for application components is inherited from ListableBeanFactory
  • The ability to load file resources in a generic way is inherited from the ResourceLoader interface
  • Inherited from ApplicationEventPublisher interface to register the listener’s ability to publish event.
  • The ability to parse messages is inherited from the MessageSource interface, enabling internationalization.
  • A single parent context can be used by the entire Web application, while each servlet has its own subcontext that is independent of any other servlet.
  • Outside of the standard BeanFactory lifecycle functionality
  • Support testing and call ApplicationContextAware and ResourceLoaderAware ApplicationEventPublisherAware and MessageSourceAware

Look at the overall logic

2. Initialize ApplicationContext

Container of initialization is primarily ApplicationContextInitializer, we’ll have a look at his family’s system

The starting point for container initialization

ApplicationContextInitializer inside is only one way

I- ApplicationContextInitializer
	M- void initialize(C applicationContext)
        
    
// This method is called in three places
 C- DelegatingApplicationContextInitializer # applyInitializers
 C- ContextLoader # customizeContext
 C- SpringApplication # applyInitializers  

Copy the code

For the main C-Spring application we’re going to look at, let’s first look at the main method, where the run method deals with the Context in several places

public ConfigurableApplicationContext run(String... args) {
    / /... Create the Application Context
	context = createApplicationContext();
	/ /... Container preprocessing
	prepareContext(context, environment, listeners, applicationArguments, printedBanner);
    / /... Container refresh operation
	refreshContext(context);
}
Copy the code

Look at the nodes one by one

Step 1: Create containers

C01- SpringApplication M1_30- createApplicationContext ? - For details, please refer to the main Application process. Here mainly through webApplicationType created three different ApplicationContext AnnotationConfigServletWebServerApplicationContext - AnnotationConfigReactiveWebServerApplicationContext - AnnotationConfigApplicationContext// M1_30 pseudo-code
protected ConfigurableApplicationContext createApplicationContext(a) { Class<? > contextClass =this.applicationContextClass;
    if (contextClass == null) {
        // Build according to type
        switch (this.webApplicationType) {
            case SERVLET:
                contextClass = Class.forName(DEFAULT_SERVLET_WEB_CONTEXT_CLASS);
                break;
            case REACTIVE:
                contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS);
                break;
            default: contextClass = Class.forName(DEFAULT_CONTEXT_CLASS); }}return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);
}
        
Copy the code

PS: if we use for SpringMVC, usually created usually AnnotationConfigServletWebServerApplicationContext

C01 - SpringApplication M1_35 - prepareContext: perfect the containers - postProcessApplicationContext: Setting the Context - applyInitializers(Context) properties - Publishing a contextPrepared listener event - If it's lazy loading, Add BeanFactoryPostProcessor - publishes a contextLoaded listener M1_37- applyInitializers FOR- All getInitializers that the loop gets, Perform the initialize? - there were performed DelegatingApplicationContextInitializer M1_39 postProcessApplicationContext - setting the Context the BeanFactory beanName The generator? - org. Springframework. Context. The annotation. InternalConfigurationBeanNameGenerator - set ResourceLoader - set this - Set the Context the BeanFactory ConversionService? - ApplicationConversionServiceCopy the code

Pseudo code — — — — >

// M1_35 core code
private void prepareContext(ConfigurableApplicationContext context, ConfigurableEnvironment environment, SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments, Banner printedBanner) {
        context.setEnvironment(environment);
        postProcessApplicationContext(context);
        // Core operation: initialize container properties
        applyInitializers(context);
        listeners.contextPrepared(context);
        if (this.logStartupInfo) {
            logStartupInfo(context.getParent() == null);
            logStartupProfileInfo(context);
        }
        // Add boot specific singleton beans
        ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
        beanFactory.registerSingleton("springApplicationArguments", applicationArguments);
        if(printedBanner ! =null) {
            beanFactory.registerSingleton("springBootBanner", printedBanner);
        }
        if (beanFactory instanceof DefaultListableBeanFactory) {
            ((DefaultListableBeanFactory) beanFactory)
                    .setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
        }
        if (this.lazyInitialization) {
            context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor());
        }
        // Load the sources
        Set<Object> sources = getAllSources();
        Assert.notEmpty(sources, "Sources must not be empty");
        load(context, sources.toArray(new Object[0]));
        listeners.contextLoaded(context);
}      
Copy the code

At the heart of the code is applyInitializers:

// M1_37 pseudo-code
protected void applyInitializers(ConfigurableApplicationContext context) {
    // getInitializers -> PS:M1_37_01
    for (ApplicationContextInitializer initializer : getInitializers()) {
            / /... Omit the assertion operation to determine whether the current class can be initializerinitializer.initialize(context); }}Copy the code

Here you can see, the For loop performed many ApplicationContextInitializer class, their container configuration related properties respectively

Related processing

C07- DelegatingApplicationContextInitializer ? - based on the context environment variable configuration., initializer. Classes configured ApplicationContextInitializer class, Initialized to them I - ApplicationContextInitializer I - Ordered M7_01 - the initialize (ConfigurableApplicationContext context) - > call #getInitializerClasses(ConfigurableEnvironment env)? - get ApplicationContextInitializer set the environment variable configuration - > call # applyInitializerClasses method, Execute the initialization m-getInitializerClasses -> Get the properties of the environment variable configuration -> assemble as an array, comma separated m-ApplyInitializerclasses method P- ConfigurableApplicationContext context P- List<Class<? > > initializerClasses - > traversal initializerClasses, create the corresponding ApplicationContextInitializer, Join the initializers - > execute ApplicationContextInitializer initialization logic - > sort first, To execute the M - the initialize (ConfigurableApplicationContext context) | - () method gets the environment variable configuration ApplicationContextInitializer collection | - if not empty, Initialized is M - getInitializerClasses (ConfigurableEnvironment env) | | - get environment variable configuration - comma-delimited, assemble the List - > classes | - Return Classes M - getInitializerClasses (String className) | - ClassUtils get full name of the class the corresponding class M - applyInitializerClasses C08 - ContextIdApplicationContextInitializer : Responsible for generating the serial number of the Spring container I - ApplicationContextInitializer I - Ordered M8_01 - the initialize (ConfigurableApplicationContext Call # getContextId applicationContext) - > (ConfigurableApplicationContext applicationContext) method,? - Get (create) ContextId object -> Set ContextId to ApplicationContext. id -> Register ContextId to Spring container M- GetContextId (ConfigurableApplicationContext applicationContext) | - get applicationContext - > applicationContext.getParent(); B - > ApplicationContext contains ContextId class | - returned directly - > parent. The getBean (ContextId. Class). CreateChildId () E - > or build new ContextId | -newContextId()-> P-getApplicationId(applicationContext.getEnvironment()) C09- ConfigurationWarningsApplicationContextInitializer : To check the configuration, Report errors configuration I - ApplicationContextInitializer M9_01 - the initialize (ConfigurableApplicationContext context) - registration ConfigurationWarningsPostProcessor into the Spring container C10 - RSocketPortInfoApplicationContextInitializer: The socket connection configuration M10_01 - the initialize (ConfigurableApplicationContext applicationContext) - addApplicationListener: Adds a Listener C11 - ServerPortInfoApplicationContextInitializer? - monitor EmbeddedServletContainerInitializedEvent types of events, Then the embedded Web server ports used to set into the ApplicationContext I - ApplicationContextInitializer I - ApplicationListener M11_01 - the initialize | - itself as an ApplicationListener listener, added to the Spring container M - onApplicationEvent? - when listening to WebServerInitializedEvent events, To trigger the | - access to the property name - > local + name + port splicing | - set port to the environment PropertyName M - getName (WebServerApplicationContext context) |- Context.getServerNamespace() M- setPortProperty(ApplicationContext context, String propertyName,intPort) | - set port to the enviroment propertyName | - if there is a parent container, continues to set the M - setPortProperty (ConfigurableEnvironment propertyName, Port) | - access to the server. The ports properties corresponding to the value of B - if the source isnull, create MapPropertySource C12 - ConditionEvaluationReportLoggingListener M12_01 - the initialize (ConfigurableApplicationContext ApplicationContext) - also joined a ConditionEvaluationReportListener C13 - SharedMetadataReaderFactoryContextInitializer? - it will create a for Shared between ConfigurationClassPostProcessor and Spring Boot CachingMetadataReaderFactory I - Bean object ApplicationContextInitializer I- OrderedCopy the code

Additional operating ComponentScanPackageCheck

C - ComponentScanPackageCheck I - Check the M - getWarning - > call # getComponentScanningPackages (BeanDefinitionRegistry registry) Methods,? - get to scan the bag collection - > - > scan names = registry. GetBeanDefinitionNames ();// Get all BeanDefinition namesFOR -> names -> AnnotatedBeanDefinition, if there is@ComponentScan-> getProblematicPackages(Set<String> scannedPackages) Get the packages to scan -> determine which scannedPackages are in the PROBLEM_PACKAGES -> If they are in the PROBLEM_PACKAGES, add them to the problemPackageCopy the code

3. Business logic of ApplicationContext

Having looked at the initialization logic of ApplicationContext above, let’s look at the business logic

The core of the business process is class AbstractApplicationContext, SpringBoot starts, the logic of processing part of the Context in the class

C50- AbstractApplicationContext
 	// The supported ApplicationContext function
	M- void setId(String id)
	M- void setDisplayName(String displayName)   
	M- void setEnvironment(ConfigurableEnvironment environment)
	M- ConfigurableEnvironment createEnvironment(a)
        // Allow events to be published
	M- void publishEvent(ApplicationEvent event)
	M- void publishEvent(Object event)
 	M- void publishEvent(Object event, @Nullable ResolvableType eventType)
        // The main get method
	M- ApplicationEventMulticaster getApplicationEventMulticaster(a)
	M- LifecycleProcessor getLifecycleProcessor(a)
	M- ResourcePatternResolver getResourcePatternResolver(a)
        // Initialize the operation
	M50_20- void initMessageSource(a)
	M50_21- void initApplicationEventMulticaster(a)
	M50_22- void initLifecycleProcessor(a)
	M50_23- void initApplicationEventMulticaster(a)
        M50_24- void registerListeners(a)
	M50_27- void initPropertySources(a)
        // Main operation
        M- void resetCommonCaches(a)
        M- void registerShutdownHook(a)
        M- void destroy(a)
        M- void close(a)
        M50_25- void doClose(a)
        M- void destroyBeans(a)
        // Core method detail
	M50_2- void refresh(a) 
	M50_10- void setParent(@Nullable ApplicationContext parent)
	M50_11- void addBeanFactoryPostProcessor(BeanFactoryPostProcessor postProcessor)
	M50_12- void addApplicationListener(ApplicationListener
        listener)
	M50_13- void prepareRefresh(a)
	M50_14- void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory)
	M50_15- void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory)
	M50_16- void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory)
	M50_17- void finishRefresh(a)
	M50_18- void cancelRefresh(BeansException ex)
	M50_30- void start(a)
	M50_31- void stop(a)
	M50_13- boolean isRunning(a)
	M50_32- void postProcessBeanFactory(a) 
	M50_33- void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory)
        // Get the Bean operation
	M- Object getBean(String name)
	M- <T> T getBean(String name, Class<T> requiredType)
	M- Object getBean(String name, Object... args)
	M- <T> T getBean(Class<T> requiredType)
	M- <T> T getBean(Class<T> requiredType, Object... args)
	M- <T> ObjectProvider<T> getBeanProvider(Class<T> requiredType)
	M- <T> ObjectProvider<T> getBeanProvider(ResolvableType requiredType)
	M- <T> Map<String, T> getBeansOfType(@Nullable Class<T> type)
	M- String[] getBeanNamesForType(ResolvableType type)
	M- String[] getBeanDefinitionNames(a)
	M- <A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType)
	M- Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType)
	M- String[] getBeanNamesForAnnotation(Class<? extends Annotation> annotationType)
	M- boolean containsLocalBean(String name)
         / / determine the Bean
	M- boolean containsBean(String name)
	M- boolean isSingleton(String name)
	M- boolean isPrototype(String name)
	M- boolean isTypeMatch(String name, ResolvableType typeToMatch)
	M- boolean containsBeanDefinition(String beanName)
         // Other operations
	M- String getMessage(...).
	M- MessageSource getMessageSource(a)

Copy the code

Let’s look at the related method functions in turn:

Module 1: Identify the function of an attribute. The common attributes are Id and Environment

M- void setId(String id)? - ContextIdApplicationContextInitializer # set in the initialize? - This ID will be used to set beanFactory SerializationId M-void setDisplayName(String displayName) 
M- void setEnvironment(ConfigurableEnvironment environment)? - SpringApplication # prepareContext set M- ConfigurableEnvironmentcreateEnvironment(a)? In - PS: AnnotatedBeanDefinitionReader getOrCreateEnvironment can create directlyCopy the code

Module 2: Event publishing

M- void publishEvent(ApplicationEvent event)
M- void publishEvent(Object event)
M- void publishEvent(Object event, @Nullable ResolvableType eventType)? If the event passed in is ApplicationEvent, it will be used directly. If not, it will be converted to PayloadApplicationEvent. If earlyApplicationEvents is enabled, Belong to, or by publishing ApplicationEventMulticaster? - ApplicationEventMulticaster object is used to notify all observer, belongs to the observer design pattern of Subject object - the parent container is empty, not the parent. PublishEventCopy the code

Module 3: The main get method

M- ApplicationEventMulticaster getApplicationEventMulticaster(a): Obtains the multicast processor M-LifecyCleProcessorgetLifecycleProcessor(a): Returns the internal LifecycleProcessor used by the context? - LifecycleProcessor: Policy interface m-ResourcepatternResolver for processing lifecycle beans in ApplicationContextgetResourcePatternResolver(a)? - used tolocation (for example, Ant Location)Policy interface resolved to resource objectCopy the code

Module 4: Initialization

M50_20- void initMessageSource(a): Initialize the MessageSource - get ConfigurableListableBeanFactory, determine whether include MessageSource TRUE - get MessageSource, And set ParentMessageSource? - hms.setParentMessageSource(getInternalParentMessageSource()) FALSE- create a new DelegatingMessageSource and set ParentMessageSource - set the current MessageSource to beanFactory? - beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource)
             
M- void initApplicationEventMulticaster(a): initialize ApplicationEventMulticaster? - ApplicationEventMulticaster: many ApplicationListener management object and release them the event? - If the context is not defined, Use SimpleApplicationEventMulticaster - get ConfigurableListableBeanFactory, Determine whether contains applicationEventMulticaster TRUE - contains from the beanFactory FALSE - build a SimpleApplicationEventMulticaster, And registerSingleton registers M-void initLifecycleProcessor(a)- in the same way, from ConfigurableListableBeanFactory determine whether exists lifecycleProcessor - is available, there is no a DefaultLifecycleProcessor M - is createdvoid initApplicationEventMulticaster(a)- in the same way, from ConfigurableListableBeanFactory determine whether exists applicationEventMulticaster - is available, Does not exist, create a SimpleApplicationEventMulticaster M50_24 -void registerListeners(a)- Obtain the current Context Set<ApplicationListener<? > >, added to the ApplicationEventMulticaster - through ApplicationListener type( getBeanNamesForType), added to the ApplicationEventMulticaster - choose the appropriate listener to handle the current earlyApplicationEventsCopy the code

Module 5: Main operations

M- void resetCommonCaches(a): Reset the cache? - including ReflectionUtils/AnnotationUtils/ResolvableType/CachedIntrospectionResults M -void registerShutdownHook(a)
M- void destroy(a)- Call close M-void close(a)- Call doClose M50_25 -void doClose(a): Executes the final logic M-void destroyBeans(a) 
Copy the code

M50_25 pseudo code

protected void doClose(a) {
        // Check whether an actual close attempt is necessary...
        if (this.active.get() && this.closed.compareAndSet(false.true)) {
            LiveBeansView.unregisterApplicationContext(this);
            
            publishEvent(new ContextClosedEvent(this));
            // Stop all Lifecycle beans to avoid delays during a single destruction
            if (this.lifecycleProcessor ! =null) {
                    this.lifecycleProcessor.onClose();
            }

            // Destroy all cached singletons in the context BeanFactory
            destroyBeans();

            // Turn off the state of the context itself.
            closeBeanFactory();

            // Let subclasses do some final cleaning if they like
            onClose();

            // Reset the local application listener to the pre-refresh state.
            if (this.earlyApplicationListeners ! =null) {
                this.applicationListeners.clear();
                this.applicationListeners.addAll(this.earlyApplicationListeners);
            }

            // Switch the Active state.
            this.active.set(false); }}Copy the code

The most important core logic series

// Core method detail
    M50_2- void refresh(a): Refresh the container main process - call prepareRefresh - > M50_13 - get ConfigurableListableBeanFactory, And invoke prepareBeanFactory pre - processing - > M50_14 - call postProcessBeanFactory - > M50_32 - call registerBeanPostProcessors - > M50_33 Call - call initMessageSource - > M50_20 - initApplicationEventMulticaster - > onRefresh M50_21 - call - > need to subclass implementation - calls the method RegisterListeners - > M50_24 - call finishBeanFactoryInitialization completed the BeanFactory initialization process - > M50_16 - call finishRefresh - > finishRefresh M50_17 M50_10-void setParent(@Nullable ApplicationContext parent): Sets the parent container M50_11-void addBeanFactoryPostProcessor(BeanFactoryPostProcessor postProcessor)
    M50_12- void addApplicationListener(ApplicationListener
        listener): Adds event listener M50_13-void prepareRefresh(a): Preprocessing - Preprocessing, first set the status: close active - callinitPropertySources (Empty implementation)- check enviroment validateRequiredProperties - if earlyApplicationListeners is empty, Will the current applicationListeners all exist to join - if earlyApplicationListeners, Will applicationListeners replaced with earlyApplicationListeners listener - reset earlyApplicationEvents M50_14 -void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory)- Sets various properties for the current beanFactory M50_15-void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory)? Do 2 class - method - call PostProcessorRegistrationDelegate. InvokeBeanFactoryPostProcessors - if there is a Bean, Add BeanPostProcessor + TempClassLoader M50_16- to beanFactoryvoid finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory)- If ConversionService exists, Set up ConversionService for the BeanFactory - add EmbeddedValueResolver as appropriate - start LoadTimeWeaverAware beans early to allow their converters to be registered early? - By triggeringgetBean(weaverAwareName)Get - Stop using temporary Classloaders for type matching - allow caching of all bean definition metadata - instantiate any remaining(not lazy - init)Singleton M50_17 -void finishRefresh(a)- Clears the context-level resource cache(for example, scan for ASM metadata)- Initialize the lifecycle processor for this context - first propagate the refresh to the lifecycle processor - publish the final event - register the current ApplicationContext with LiveBeansView M50_18-void cancelRefresh(BeansException ex)- Modify status ->this.active.set(false
    M50_30- void start()- Start life cycle managementgetLifecycleProcessor(a).start(a); Publish a publishEvent event ContextStartedEvent M50_31-void stop(a)- Start life cycle managementgetLifecycleProcessor(a).stop(a)- Publish event ContextStoppedEvent M50_13-boolean isRunning(a)- determine lifecycleProcessor.isRunning(a)                  
    M50_32- void postProcessBeanFactory(a)- Empty implementation, modifying its internal bean factory after the standard initialization of the application context - this method handles M50_33- in subclassesvoid registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory)- call PostProcessorRegistrationDelegate # registerBeanPostProcessors method? -> M50_27-void initPropertySources(a)

Copy the code

M50_2 pseudo-code, go back and look at the process

    @Override
    public void refresh(a) throws BeansException, IllegalStateException {
        synchronized (this.startupShutdownMonitor) {
            // Prepare this context for refresh -> M50_13
            prepareRefresh();

            // Tell the subclass to refresh the internal bean factory.
            ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

            // Tell the subclass to refresh the internal bean factory
            prepareBeanFactory(beanFactory);

            try {
                // Allow post-processing of bean factories in context subclasses
                postProcessBeanFactory(beanFactory);

                // Call the factory handler registered as a bean in the context
                // This is where the main logic of IOC lies
                invokeBeanFactoryPostProcessors(beanFactory);

                // Register the Bean handler created by the intercepting Bean
                registerBeanPostProcessors(beanFactory);

                // Initialize the message source for this context
                initMessageSource();

                // Initialize the event multi-master for this context.
                initApplicationEventMulticaster();

                // Initialize other special beans in a particular context subclass.
                onRefresh();

                // Check the listener beans and register them.
                registerListeners();

                // Instantiate all remaining (non-lazy-init) singletons.
                finishBeanFactoryInitialization(beanFactory);

                // Last step: publish the corresponding event
                finishRefresh();
            }catch (BeansException ex) {
            
                // Destroy the created singleton to prevent the resource from dangling
                destroyBeans();

                // Reset the "active" flag.
                cancelRefresh(ex);

                // Propagates the exception to the caller.
                throw ex;
            }

            finally {
                // Reset common introspection caches in Spring's core, since we
                // might not ever need metadata for singleton beans anymore...resetCommonCaches(); }}}Copy the code

BeanPostProcessors has enough processes to open a chapter on them, so I won’t mention them here

What it does: Allows custom changes to bean definitions in the application context, and can adjust the bean property values of the underlying bean factory in the context: BeanFactoryPostProcessor can interact with bean definitions and modify them, but never interact with bean instances

The main call ConfigurationClassPostProcessor, including processing processConfigBeanDefinitions

C52 - PostProcessorRegistrationDelegate M52_01 invokeBeanFactoryPostProcessors - call the given spring BeanFactoryPostProcessor bean M52_02 registerBeanPostProcessors - register given BeanPostProcessor beanCopy the code

registerBeanPostProcessors


private static void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory, List<BeanPostProcessor> postProcessors) {
    for(BeanPostProcessor postProcessor : postProcessors) { beanFactory.addBeanPostProcessor(postProcessor); }}Copy the code

DefaultLifecycleProcessor process

C53- DefaultLifecycleProcessor ? - Policy interface for processing lifecycle beans in ApplicationContext M53_01- startBeans - M53_02- stopBeans M53_03- doStart M53_04- doStop M53_05- GetLifecycleBeans () : Retrieves all applicable lifecycle beansCopy the code
  • Lifecycle interface:
    • Defines the public interface for the start/stop lifecycle control method
    • It can be beans and containers
    • When the ApplicationContext itself starts and stops, it automatically invokes the implementation of all life cycles within the context
  • LifecycleProcessor interface:
    • LifecycleProcessor is responsible for managing the ApplicationContext lifecycle
    • LifecycleProcessor itself extends the Lifecycle interface. It also adds two other methods to interact with the context, making it possible to refresh and close
    • LifecycleProcessor’s onRefresh and onClose are the more important methods
      • The onRefresh function is that the container is started successfully
      • OnClose is only when the application is to be closed
  • DefaultLifecycleProcessor
    • The default LifecycleProcessor implementation is primarily responsible for all LifecycleProcessor implementation execution
    • DefaultLifecycleProcessor is LifecycleProcessor proxy objects.

M50_14: pseudocode

protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
        // Tell the internal bean factory to use the context's class loader etc.
        beanFactory.setBeanClassLoader(getClassLoader());
        beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
        beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

        // Configure the bean factory with context callbacks.
        beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
        beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
        beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
        beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
        beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
        beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
        beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);

        // BeanFactory interface not registered as resolvable type in a plain factory.
        // MessageSource registered (and found for autowiring) as a bean.
        beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
        beanFactory.registerResolvableDependency(ResourceLoader.class, this);
        beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
        beanFactory.registerResolvableDependency(ApplicationContext.class, this);

        // Register early post-processor for detecting inner beans as ApplicationListeners.
        beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

        // Detect a LoadTimeWeaver and prepare for weaving, if found.
        if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
            beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
            // Set a temporary ClassLoader for type matching.
            beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
        }

        // Register default environment beans.
        if(! beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) { beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment()); }if(! beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) { beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME,  getEnvironment().getSystemProperties()); }if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
            beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
        }
    }

Copy the code

M50_16 finishBeanFactoryInitialization

M50_16- void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory)- Add EmbeddedValueResolver as appropriate - Start LoadTimeWeaverAware beans early to allow their converters to be registered early? - By triggeringgetBean(weaverAwareName)Get - Stop using temporary Classloaders for type matching - allow caching of all bean definition metadata - instantiate any remaining(not lazy - init)The singletonprotected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
        // Set the ConversionService for the BeanFactory if it exists
        if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
                beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
            beanFactory.setConversionService(
                    beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
        }

        // Add the EmbeddedValueResolver as required
        if(! beanFactory.hasEmbeddedValueResolver()) { beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal)); }// Start LoadTimeWeaverAware beans early to allow their converters to be registered early
        String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false.false);
        for (String weaverAwareName : weaverAwareNames) {
            // By triggering getBean(weaverAwareName)
            getBean(weaverAwareName);
        }

        // Stop using a temporary ClassLoader for type matching
        beanFactory.setTempClassLoader(null);

        // Allow caching of all bean definition metadata
        beanFactory.freezeConfiguration();

        // Instantiate all remaining (non-lazy-init) singletons
        beanFactory.preInstantiateSingletons();
    }

Copy the code

conclusion

The entire ApplicationContext process is complete, and once the process is complete, you can begin the IOC Bean loading process.

Write really tired, concrete logic diagram should be more or less