When your talent doesn't support your ambition , Only calm down to learn .
<>1. brief introduction

        In research spring Before source code , First, make sure you've used it spring Framework development project , Have some basic knowledge , Like knowing what it is beanFactory,Ioc, Dependency injection, etc , And it's best to know the principle simply . because spring The source code system is huge , It can't be done. It involves every detail , Can only explain his core functions , One chapter cannot be summarized in full , It may be divided into several chapters . be studying at school or research institute spring Source code in the process , If the harvest is not too big , Or do you need to manually adjust the source code . This chapter is based on
Annotation method (AnnotationConfigApplicationContext)
For interpretation . Write test cases to simulate spring Loading process , When you understand spring The work flow of his talk about how to carry out integration .
Be sure to read the source code yourself , Remember to read the source code , Don't cling to details , To use the object-oriented thinking to interpret , Just know what this code does for us , If you want to know more , You can click in and study it in depth , Otherwise, the code segment is too long , It's easy to get dizzy and not easy to read .
        Take a project as an example , see spring How does it work , The structure is as follows , Use any one spring The project is OK , Not much :

        Write a test class , conduct spring load :
@ComponentScan("com.online.manager") public class AppController { public static
void main(String[] args) { AnnotationConfigApplicationContext context = new
AnnotationConfigApplicationContext(AppController.class); // TODO1
To this point spring Loading completed UserController userController = context.getBean(UserController.
class); } }
        When the test is executed to context.getBean When ,spring The container has been loaded , All we need to see new
AnnotationConfigApplicationContext What did the bottom floor do . When you click to enter
AnnotationConfigApplicationContext Class (ctrl + mouse ) When , We're going into this construction method :
public AnnotationConfigApplicationContext(Class... annotatedClasses) { // this
Is to call its own parameterless constructor , Click to view // This chapter only deals with this this What did you do , Don't look at his simplicity , It's actually very deep this(); // Next time this.register
(annotatedClasses); this.refresh(); }
        You can see the first line of code this();
What he calls is his own nonparametric constructor , because java The property knows that it is calling its own nonparametric constructor , The nonparametric constructor of the parent class is called first , So let's go into his father first
(GenericApplicationContext) See his parameterless construction in .

       GenericApplicationContext Nonparametric construction method :
// This property of the parent class is very important , He is spring Our factory private final DefaultListableBeanFactory
beanFactory; public GenericApplicationContext() { this.customClassLoader = false
; this.refreshed = new AtomicBoolean(); // Initializes the factory in the parent constructor ( Very important ) this.beanFactory
= new DefaultListableBeanFactory(); }
        stay GenericApplicationContext
In the class of , You can see that he has a very important attribute , That's what we often say bean factory beanFactory, If you want to see his attributes, click in to check them , See what properties he has . His construction method is our bean The factory is instantiated spring factory (
It's just created but not initialized ). This is it. beanFactory The real body of , If you want to learn more, you can continue to search GenericApplicationContext
What did our parent class do for us , This is not an overview .

        Based on inheritance ,AnnotationConfigApplicationContext Class holds this beanFactory An example of , Very important .
The constructor of the parent class is finished , Let's look at our own construction method .( Don't get dizzy )

        AnnotationConfigApplicationContext Nonparametric construction method :
public AnnotationConfigApplicationContext() { //
Pass an instance of itself to his constructor , An annotation is created bean Define reader , Used to parse our configuration class into BeanDefinition. Very important this.reader =
new AnnotatedBeanDefinitionReader(this); //
Create a bean Define scanner , Manually called externally , use scan Methods scanning was performed , Not important, adjustable this.scanner = new
ClassPathBeanDefinitionScanner(this); }
      AnnotationConfigApplicationContext The construction method of the (this) Pass past call
AnnotatedBeanDefinitionReader To create an annotation bean Define reader , Function is used to parse our configuration class into BeanDefinition
Put into beanFactory Of beanDefinitionMap Attribute .

        Why do I have to report this Pass it on ? Think about it ?
        Because of this this yes AnnotationConfigApplicationContext
An example of , And because of his parentage , So he held it himself bean Examples of factories . So you can come through this Get our beanFactory factory .

        But in the AnnotatedBeanDefinitionReader(this)
This method of construction helps us to do a lot of things , The code is very important here , The main thing is to finish beanFactory Initial plant initialization , Look down .

       AnnotatedBeanDefinitionReader(this) Construction method :
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry) { this(
registry, getOrCreateEnvironment(registry)); } // The constructor of the final call public
AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment
environment) { ..... Less important code omission , Mainly complete the initialization // Very important -- complete `beanFactory` Initial plant initialization
AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry); }
        You can see this on the top BeanDefinitionRegistry registry The parameters are actually ours
AnnotationConfigApplicationContext realization ( You can view class relationships by looking at class relationships ,
AnnotationConfigApplicationContext yes BeanDefinitionRegistry An implementation of ), It will eventually call
registerAnnotationConfigProcessors This method .

       registerAnnotationConfigProcessors method ( Very important ):
public static void registerAnnotationConfigProcessors(BeanDefinitionRegistry
registry) { registerAnnotationConfigProcessors(registry, (Object)null); } //
Finally, this method is called public static Set<BeanDefinitionHolder>
registerAnnotationConfigProcessors(BeanDefinitionRegistry registry, @Nullable
Object source) { // In this way , from registry To get our bean factory , You can check the details by yourself (ctrl + Click method ) //
Implementation is hold registry Forced to GenericApplicationContext, Call him getDefaultListableBeanFactory Get factory
DefaultListableBeanFactory beanFactory= unwrapDefaultListableBeanFactory(
registry); // The factory was built before , It must not be empty //
Here's the code bean The initialization of the factory is working , All we need to know is that these properties are populated for our factory , To use these features later if (beanFactory != null) { if (
!(beanFactory.getDependencyComparator() instanceof
AnnotationAwareOrderComparator)) { //
Added comparator for sorting ,( handle Ordered Interface ,PriorityOrdered Interface function ) beanFactory.setDependencyComparator
(AnnotationAwareOrderComparator.INSTANCE); } if (!(beanFactory.
getAutowireCandidateResolver() instanceof
ContextAnnotationAutowireCandidateResolver)) { // Provides the function of delayed loading beanFactory.
setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
} } Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet(8);
RootBeanDefinition def; // Registered with the factory 7 Post processors are very important and complete spring Core functions of if (!registry.
)) { def = new RootBeanDefinition(ConfigurationClassPostProcessor.class); def.
setSource(source); // towards beanDefinitionMap join ConfigurationClassPostProcessor Post Processors
// What he achieved was BeanDefinitionRegistryPostProcessor Interface //
Mainly complete the user-defined class (@Configuration,@Componet,@Serveice,@Import annotation ) Scan for , Add our defined classes to the spring In the container
// It will be introduced in detail later beanDefs.add(registerPostProcessor(registry, def,
)); } if (!registry.containsBeanDefinition(
{ def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class); def.
setSource(source); //
towards beanDefinitionMap join AutowiredAnnotationBeanPostProcessor Post Processors //
What he achieved was BeanFactoryPostProcessor Interface , handle @Autowired, complete bean The work of attribute injection beanDefs.add(
registerPostProcessor(registry, def,
} // Check for JSR-250 support, and if present add the
CommonAnnotationBeanPostProcessor. if (jsr250Present && !registry.
RootBeanDefinition def= new RootBeanDefinition(CommonAnnotationBeanPostProcessor
.class); def.setSource(source); //
towards beanDefinitionMap join CommonAnnotationBeanPostProcessor Post Processors //
What he achieved was BeanFactoryPostProcessor Interface , handle @Resource and JSR 250 annotation beanDefs.add(
registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)); }
//jpa function if (jpaPresent && !registry.containsBeanDefinition(
RootBeanDefinition(); try { def.setBeanClass(ClassUtils.forName(
getClassLoader())); } catch (ClassNotFoundException ex) { throw new
IllegalStateException( "Cannot load optional framework class: " +
beanDefs.add(registerPostProcessor(registry, def,
RootBeanDefinition def= new RootBeanDefinition(EventListenerMethodProcessor.
class); def.setSource(source); // Injection event monitoring method beanDefs.add(registerPostProcessor(
registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME)); } if (!registry.
containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) { RootBeanDefinition
def= new RootBeanDefinition(DefaultEventListenerFactory.class); def.setSource(
source); // Inject default event listening factory beanDefs.add(registerPostProcessor(registry, def,
This method is very important , complete beanFactory Initialization of the , towards beanDefinitionMap Registered in 7 Post processor BeanDefinition Information for , among
CommonAnnotationBeanPostProcessor These three post processors are very important , among ConfigurationClassPostProcessor
This post processor is the top priority , It will be explained in the follow-up use , It's just a thought beanFactory Set in , But it wasn't used , Convenience didn't know how it came into being in the subsequent process .

        Come here AnnotationConfigApplicationContext In the nonparametric construction method of new
AnnotatedBeanDefinitionReader(this) This line of code is finished . The execution new
This code , In fact, this code is not very useful , It is mainly provided for external use by programmers themselves , unimportance , If you are interested, you can check it by yourself .

        Come here AnnotationConfigApplicationContext In the construction method of this()
The method is executed , There are many details that have not been explained clearly , If you can, you can check it by yourself .

©2019-2020 Toolsou All rights reserved,
One is called “ Asking for the train ” A small village Finally got the train Spring Boot Lesson 16 :SpringBoot Implementation of multithreading with injection class Chrome OS, For programmers and Windows What does it mean ? Internet Marketing JAVA Convert a string to a numeric type I've been drinking soft water for three years ? What is the use of soft water and water softener You don't know ——HarmonyOS Talking about uni-app Page value transfer problem JavaScript Medium Call and ApplySparkSQL Achieve partition overlay write Character recognition technology of vehicle license plate based on Neural Network