+
+## 容器创建
+
+```java
+public class AnnotationMainTest {
+
+ public static void main(String[] args) {
+
+ ApplicationContext applicationContext =
+ new AnnotationConfigApplicationContext(MainConfig.class);
+ }
+```
+
+
+
+### AnnotationConfigApplicationContext有参构造
+
+```java
+ public AnnotationConfigApplicationContext(Class>... componentClasses) {
+ this();
+ register(componentClasses);
+ refresh(); //容器完整刷新(创建出所有组件,组织好所有功能)
+ }
+```
+
+#### AnnotationConfigApplicationContext#this()无参构造
+
+```java
+ // 上面的this()就是调用的这里
+ public AnnotationConfigApplicationContext() {
+ StartupStep createAnnotatedBeanDefReader = this.getApplicationStartup().start("spring.context.annotated-bean-reader.create");
+ this.reader = new AnnotatedBeanDefinitionReader(this);
+ createAnnotatedBeanDefReader.end();
+ this.scanner = new ClassPathBeanDefinitionScanner(this);
+ }
+```
+
+##### AnnotatedBeanDefinitionReader有参构造
+
+```java
+ public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry) {
+ this(registry, getOrCreateEnvironment(registry));
+ }
+
+ public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
+ Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
+ Assert.notNull(environment, "Environment must not be null");
+ this.registry = registry;
+ this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);
+ AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
+ }
+```
+
+##### AnnotationConfigUtils#registerAnnotationConfigProcessors()注册Spring内部几个核心组件
+
+```java
+ /**
+ * The bean name of the internally managed Configuration annotation processor.
+ */
+ public static final String CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME =
+ "org.springframework.context.annotation.internalConfigurationAnnotationProcessor";
+
+ /**
+ * The bean name of the internally managed BeanNameGenerator for use when processing
+ * {@link Configuration} classes. Set by {@link AnnotationConfigApplicationContext}
+ * and {@code AnnotationConfigWebApplicationContext} during bootstrap in order to make
+ * any custom name generation strategy available to the underlying
+ * {@link ConfigurationClassPostProcessor}.
+ * @since 3.1.1
+ */
+ public static final String CONFIGURATION_BEAN_NAME_GENERATOR =
+ "org.springframework.context.annotation.internalConfigurationBeanNameGenerator";
+
+ /**
+ * The bean name of the internally managed Autowired annotation processor.
+ */
+ public static final String AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME =
+ "org.springframework.context.annotation.internalAutowiredAnnotationProcessor";
+
+ /**
+ * The bean name of the internally managed Required annotation processor.
+ * @deprecated as of 5.1, since no Required processor is registered by default anymore
+ */
+ @Deprecated
+ public static final String REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME =
+ "org.springframework.context.annotation.internalRequiredAnnotationProcessor";
+
+ /**
+ * The bean name of the internally managed JSR-250 annotation processor.
+ */
+ public static final String COMMON_ANNOTATION_PROCESSOR_BEAN_NAME =
+ "org.springframework.context.annotation.internalCommonAnnotationProcessor";
+
+ /**
+ * The bean name of the internally managed JPA annotation processor.
+ */
+ public static final String PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME =
+ "org.springframework.context.annotation.internalPersistenceAnnotationProcessor";
+
+ private static final String PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME =
+ "org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor";
+
+ /**
+ * The bean name of the internally managed @EventListener annotation processor.
+ */
+ public static final String EVENT_LISTENER_PROCESSOR_BEAN_NAME =
+ "org.springframework.context.event.internalEventListenerProcessor";
+
+ /**
+ * The bean name of the internally managed EventListenerFactory.
+ */
+ public static final String EVENT_LISTENER_FACTORY_BEAN_NAME =
+ "org.springframework.context.event.internalEventListenerFactory";
+
+
+ public static void registerAnnotationConfigProcessors(BeanDefinitionRegistry registry) {
+ registerAnnotationConfigProcessors(registry, null);
+ }
+
+
+
+ public static Set
+
+##### RootBeanDefinition
+
+```java
+ public RootBeanDefinition(@Nullable Class> beanClass) {
+ super();
+ setBeanClass(beanClass);
+ }
+```
+
+##### AbstractBeanDefinition
+
+```java
+ protected AbstractBeanDefinition() {
+ this(null, null);
+ }
+```
+
+##### ClassPathBeanDefinitionScanner
+
+```java
+ public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters,
+ Environment environment, @Nullable ResourceLoader resourceLoader) {
+
+ Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
+ this.registry = registry;
+
+ if (useDefaultFilters) {
+ registerDefaultFilters();
+ }
+ setEnvironment(environment); //准备环境
+ setResourceLoader(resourceLoader);//准备资源加载器
+ }
+```
+
+#### AnnotationConfigApplicationContext#register()
+
+```java
+ public void register(Class>... componentClasses) {
+ //componentClasses就是咱们的配置类
+ Assert.notEmpty(componentClasses, "At least one component class must be specified");
+ StartupStep registerComponentClass = this.getApplicationStartup().start("spring.context.component-classes.register")
+ .tag("classes", () -> Arrays.toString(componentClasses));
+ this.reader.register(componentClasses);
+ registerComponentClass.end();
+ }
+```
+
+
+
+##### AnnotatedBeanDefinitionReader#register()注册主配置类BeanDefinition
+
+```java
+ public void register(Class>... componentClasses) {
+ for (Class> componentClass : componentClasses) {
+ registerBean(componentClass);
+ }
+ }
+
+ public void registerBean(Class> beanClass) {
+ doRegisterBean(beanClass, null, null, null, null);
+ }
+
+
+ private
+
+
+
+1. 接下来就是想办法让主配置类里的配置生效
+2. 目前Spring就靠上面的4个后置处理器和一个主配置类白手起家了,开始我们后面最重要的refresh()容器刷新流程了
+
+
+
+
+
+
+
+## AbstractApplicationContext#refresh()开始容器刷新
+
+```java
+ @Override //容器刷新的十二大步。模板模式
+ public void refresh() throws BeansException, IllegalStateException {
+ synchronized (this.startupShutdownMonitor) {
+ //容器启动过程状态的封装类
+ StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");
+
+ //准备上下文环境 Prepare this context for refreshing.
+ prepareRefresh();
+
+ // Tell the subclass to refresh the internal bean factory.
+ // 工厂创建:BeanFactory第一次开始创建的时候,有xml解析逻辑。注解版这一步什么都没做,直接返回this()环节早就new好的工厂
+ ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
+
+ //给容器中注册了环境信息作为单实例Bean方便后续自动装配;放了一些后置处理器处理(监听、xxAware功能) Prepare thebean factory for use in this context.
+ prepareBeanFactory(beanFactory);
+
+ try {
+ //留给子类的模板方法,允许子类继续对工厂执行一些处理; Allows post-processing of the bean factory in context subclasses.
+ postProcessBeanFactory(beanFactory);
+
+ StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
+ //【核心】工厂增强:执行所有的BeanFactory后置增强器;利用BeanFactory后置增强器对工厂进行修改或者增强,配置类会在这里进行解析。 Invoke factory processors registered as beans in the context.
+ invokeBeanFactoryPostProcessors(beanFactory);
+
+ //【核心】注册所有的Bean的后置处理器 Register bean processors that intercept bean creation.
+ registerBeanPostProcessors(beanFactory);
+ beanPostProcess.end();
+
+ //初始化国际化功能 Initialize message source for this context.
+ initMessageSource();
+
+ //初始化事件多播功能(事件派发) Initialize event multicaster for this context.
+ initApplicationEventMulticaster();
+
+ // Initialize other special beans in specific context subclasses.
+ onRefresh();
+
+ //注册监听器,从容器中获取所有的ApplicationListener; Check for listener beans and register them.
+ registerListeners();
+
+ // Instantiate all remaining (non-lazy-init) singletons.
+ //【大核心】bean创建;完成 BeanFactory 初始化。(工厂里面所有的组件都好了)
+ 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();
+ contextRefresh.end();
+ }
+ }
+ }
+```
+
+
+
+### prepareRefresh()准备上下文环境
+
+```java
+ protected void prepareRefresh() {
+ // Switch to active.
+ this.startupDate = System.currentTimeMillis();
+ this.closed.set(false);
+ this.active.set(true);
+
+ if (logger.isDebugEnabled()) {
+ if (logger.isTraceEnabled()) {
+ logger.trace("Refreshing " + this);
+ }
+ else {
+ logger.debug("Refreshing " + getDisplayName());
+ }
+ }
+
+ //其他子容器自行实现(比如:WebApplicationContext) Initialize any placeholder property sources in the context environment.
+ initPropertySources();
+
+ //准备环境变量信息 Validate that all properties marked as required are resolvable:
+ // see ConfigurablePropertyResolver#setRequiredProperties
+ getEnvironment().validateRequiredProperties();
+
+ // 存储子容器早期运行的一些监听器; Store pre-refresh ApplicationListeners...
+ if (this.earlyApplicationListeners == null) {
+ this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
+ }
+ else {
+ // Reset local application listeners to pre-refresh state.
+ this.applicationListeners.clear();
+ this.applicationListeners.addAll(this.earlyApplicationListeners);
+ }
+
+ //早期的一些事件存储到这里 Allow for the collection of early ApplicationEvents,
+ // to be published once the multicaster is available...
+ this.earlyApplicationEvents = new LinkedHashSet<>();
+ }
+```
+
+#### initPropertySources()
+
+```java
+protected void initPropertySources() {
+ // For subclasses: do nothing by default. 自行在此处加载一些自己感兴趣的信息。【WebApplicationContextUtils.initServletPropertySources】
+ // web-ioc容器启动的时候一般在此加载当前应用的上下文信息(ApplicationContext)
+}
+```
+
+
+
+### prepareBeanFactory()给BeanFactory准备一些核心组件
+
+```java
+ protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
+ // Tell the internal bean factory to use the context's class loader etc.
+ beanFactory.setBeanClassLoader(getClassLoader());
+ if (!shouldIgnoreSpel) { //解释器模式 ,解析el表达式
+ beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
+ }
+ beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
+
+ // Configure the bean factory with context callbacks.
+ beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this)); //准备一个处理Aware接口功能的后置处理器
+ beanFactory.ignoreDependencyInterface(EnvironmentAware.class); //告诉Spring先别管这些接口
+ beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
+ beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
+ beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
+ beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
+ beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
+ beanFactory.ignoreDependencyInterface(ApplicationStartupAware.class);
+
+ /*
+ 1.注册可以解析到的依赖,直接保存到容器的resolvableDependencies池里
+ 2.意思就是在我们自定义的类中,我们可以直接用@Autowired注解注入下面4个东西,并直接使用
+ */
+ beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
+ beanFactory.registerResolvableDependency(ResourceLoader.class, this);
+ beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
+ beanFactory.registerResolvableDependency(ApplicationContext.class, this);
+
+ // 注册应用监听器的探测器,用来探测应用中有哪些监听器。这也是一个后置处理器
+ beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
+
+ // Detect a LoadTimeWeaver and prepare for weaving, if found.
+ if (!NativeDetector.inNativeImage() && 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());
+ }
+ if (!beanFactory.containsLocalBean(APPLICATION_STARTUP_BEAN_NAME)) {
+ beanFactory.registerSingleton(APPLICATION_STARTUP_BEAN_NAME, getApplicationStartup());
+ }
+ }
+
+ String ENVIRONMENT_BEAN_NAME = "environment";
+
+ String SYSTEM_PROPERTIES_BEAN_NAME = "systemProperties";
+
+ String SYSTEM_ENVIRONMENT_BEAN_NAME = "systemEnvironment";
+
+ /**
+ * Name of the {@link ApplicationStartup} bean in the factory.
+ * @since 5.3
+ */
+ String APPLICATION_STARTUP_BEAN_NAME = "applicationStartup";
+
+```
+
+
+
+### postProcessBeanFactory()留给子类的模板方法
+
+这里是一个空方法,主要是留给子类实现,比如Web里的
+
+```java
+ protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
+ }
+```
+
+
+
+
+
+
+
+### invokeBeanFactoryPostProcessors()工厂增强【核心】
+
+```java
+ protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
+ PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors()); //执行所有的工厂增强器
+ //上面的类叫:后置处理器的注册代理(门面模式-装饰模式)
+ // Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
+ // (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
+ if (!NativeDetector.inNativeImage() && beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
+ beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
+ beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
+ }
+ }
+```
+
+这一步有个很关键的后置处理器
+
+
+
+
+
+
+
+
+
+#### ConfigurationClassPostProcessor#postProcessBeanDefinitionRegistry()开始解析@Configuration标注的所有配置类相关信息,并生成Bean
+
+`AnnotationConfigApplicationContext#register()`这里解析的是主配置类
+
+```java
+ @Override //把配置类中所有bean的定义信息导入进来。
+ public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
+ int registryId = System.identityHashCode(registry);
+ if (this.registriesPostProcessed.contains(registryId)) {
+ throw new IllegalStateException(
+ "postProcessBeanDefinitionRegistry already called on this post-processor against " + registry);
+ }
+ if (this.factoriesPostProcessed.contains(registryId)) {
+ throw new IllegalStateException(
+ "postProcessBeanFactory already called on this post-processor against " + registry);
+ }
+ this.registriesPostProcessed.add(registryId);
+
+ processConfigBeanDefinitions(registry); //处理配置的BeanDefinition信息
+ }
+
+
+
+ public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
+ List
+
+
+
+#### ConfigurationClassParser#parse()
+
+```java
+ public void parse(Set
+
+
+
+
+
+最后我们看一下执行完之后的BeanDefinition信息
+
+
+
+
+
+### registerBeanPostProcessors()注册所有的Bean后置处理器
+
+前面讲过
+
+```java
+ protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
+ PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
+ }
+```
+
+#### PostProcessorRegistrationDelegate#registerBeanPostProcessors()
+
+```java
+ public static void registerBeanPostProcessors(
+ ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
+
+ // WARNING: Although it may appear that the body of this method can be easily
+ // refactored to avoid the use of multiple loops and multiple lists, the use
+ // of multiple lists and multiple passes over the names of processors is
+ // intentional. We must ensure that we honor the contracts for PriorityOrdered
+ // and Ordered processors. Specifically, we must NOT cause processors to be
+ // instantiated (via getBean() invocations) or registered in the ApplicationContext
+ // in the wrong order.
+ //
+ // Before submitting a pull request (PR) to change this method, please review the
+ // list of all declined PRs involving changes to PostProcessorRegistrationDelegate
+ // to ensure that your proposal does not result in a breaking change:
+ // https://github.com/spring-projects/spring-framework/issues?q=PostProcessorRegistrationDelegate+is%3Aclosed+label%3A%22status%3A+declined%22
+ //获取到容器中所有的 BeanPostProcessor; Bean的后置处理器
+ String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
+
+ // Register BeanPostProcessorChecker that logs an info message when
+ // a bean is created during BeanPostProcessor instantiation, i.e. when
+ // a bean is not eligible for getting processed by all BeanPostProcessors.
+ int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
+ beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
+
+ // Separate between BeanPostProcessors that implement PriorityOrdered,
+ // Ordered, and the rest.
+ List
+
+
+
+## 核心代码
+
+### AbstractBeanFactory
+
+```java
+ protected Checks already instantiated singletons and also allows for an early
+ * reference to a currently created singleton (resolving a circular reference).
+ * @param beanName the name of the bean to look for
+ * @param allowEarlyReference whether early references should be created or not
+ * @return the registered singleton object, or {@code null} if none found
+ */
+ //☆☆☆ pos_4
+ @Nullable //双检查锁
+ protected Object getSingleton(String beanName, boolean allowEarlyReference) {
+ //先检查单例缓存池,获取当前对象 Quick check for existing instance without full singleton lock
+ Object singletonObject = this.singletonObjects.get(beanName); //一级缓存
+ if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) { //如果当前bean正在创建过程中,而且缓存中没有则继续
+ singletonObject = this.earlySingletonObjects.get(beanName); //二级
+ if (singletonObject == null && allowEarlyReference) {
+ synchronized (this.singletonObjects) {
+ // Consistent creation of early reference within full singleton lock
+ singletonObject = this.singletonObjects.get(beanName);
+ if (singletonObject == null) {
+ singletonObject = this.earlySingletonObjects.get(beanName);
+ if (singletonObject == null) {
+ ObjectFactory> singletonFactory = this.singletonFactories.get(beanName); //三级
+ if (singletonFactory != null) {
+ singletonObject = singletonFactory.getObject();
+ this.earlySingletonObjects.put(beanName, singletonObject);
+ this.singletonFactories.remove(beanName);
+ }
+ }
+ }
+ }
+ }
+ }
+ return singletonObject;
+ }
+
+
+ // ☆☆☆ pos_5
+ public Object getSingleton(String beanName, ObjectFactory> singletonFactory) {
+ Assert.notNull(beanName, "Bean name must not be null");
+ synchronized (this.singletonObjects) {
+ Object singletonObject = this.singletonObjects.get(beanName);//再检查一次单例池
+ if (singletonObject == null) { //单实例池子里面没有当前对象(说明没有创建完成)
+ if (this.singletonsCurrentlyInDestruction) {
+ throw new BeanCreationNotAllowedException(beanName,
+ "Singleton bean creation not allowed while singletons of this factory are in destruction " +
+ "(Do not request a bean from a BeanFactory in a destroy method implementation!)");
+ }
+ if (logger.isDebugEnabled()) {
+ logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
+ }
+ // ☆☆☆ pos_6
+ beforeSingletonCreation(beanName); //单实例创建之前,这个就是加到
+ boolean newSingleton = false;
+ boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
+ if (recordSuppressedExceptions) {
+ this.suppressedExceptions = new LinkedHashSet<>();
+ }
+ try {
+ singletonObject = singletonFactory.getObject();//会调用lamda表达式的内容,真正创建对象
+ newSingleton = true;
+ }
+ catch (IllegalStateException ex) {
+ // Has the singleton object implicitly appeared in the meantime ->
+ // if yes, proceed with it since the exception indicates that state.
+ // ☆☆☆ pos_7
+ singletonObject = this.singletonObjects.get(beanName);
+ if (singletonObject == null) {
+ throw ex;
+ }
+ }
+ catch (BeanCreationException ex) {
+ // ...
+ }
+ finally {
+ if (recordSuppressedExceptions) {
+ this.suppressedExceptions = null;
+ }
+ afterSingletonCreation(beanName);
+ }
+ if (newSingleton) {
+ addSingleton(beanName, singletonObject);
+ }
+ }
+ return singletonObject;
+ }
+ }
+
+ // 加到singletonsCurrentlyInCreation
+ protected void beforeSingletonCreation(String beanName) {
+ if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.add(beanName)) {
+ throw new BeanCurrentlyInCreationException(beanName);
+ }
+ }
+
+```
+
+### AbstractAutowireCapableBeanFactory
+
+```java
+ protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
+ throws BeanCreationException {
+
+ // Instantiate the bean.
+ BeanWrapper instanceWrapper = null;
+ if (mbd.isSingleton()) { //是否单例的
+ instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
+ }
+ if (instanceWrapper == null) {
+ //创建Bean的实例,默认使用无参构造器创建的对象,组件的原始对象就创建了 ☆☆☆ pos_8
+ instanceWrapper = createBeanInstance(beanName, mbd, args);
+ }
+ Object bean = instanceWrapper.getWrappedInstance();
+ Class> beanType = instanceWrapper.getWrappedClass();
+ if (beanType != NullBean.class) {
+ mbd.resolvedTargetType = beanType;
+ }
+
+ // ...
+
+ // 提前暴露单实例。专门来解决循环引用问题;Eagerly cache singletons to be able to resolve circular references
+ // even when triggered by lifecycle interfaces like BeanFactoryAware.
+ // ☆☆☆ pos_9
+ boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
+ isSingletonCurrentlyInCreation(beanName));
+ if (earlySingletonExposure) {
+ if (logger.isTraceEnabled()) {
+ logger.trace("Eagerly caching bean '" + beanName +
+ "' to allow for resolving potential circular references");
+ }
+ addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean)); //三级缓存中的Bean也会被后置处理来增强,
+ }
+
+ // Initialize the bean instance.
+ Object exposedObject = bean;
+ try {
+ // ☆☆☆ pos_10
+ populateBean(beanName, mbd, instanceWrapper); //给创建好的对象每个属性进行赋值,@Autowired发生在这里
+ exposedObject = initializeBean(beanName, exposedObject, mbd);//初始化bean
+ }
+ catch (Throwable ex) {
+ if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
+ throw (BeanCreationException) ex;
+ }
+ else {
+ throw new BeanCreationException(
+ mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
+ }
+ }
+ //早期单实例暴露
+ if (earlySingletonExposure) {
+ Object earlySingletonReference = getSingleton(beanName, false); //检查早期缓存中是否存在这个组件
+ if (earlySingletonReference != null) {
+ if (exposedObject == bean) {
+ exposedObject = earlySingletonReference;
+ }
+ else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
+ String[] dependentBeans = getDependentBeans(beanName);
+ Set
+
+2. 然后走到pos_2调用pos_5的`getSingleton()`开始创建A的流程
+3. 在pos_5的`getSingleton()`中走到pos_6的`beforeSingletonCreation()`,就变成下面这样
+
+
+
+4. 接着pos_7的会调用pos_2的lamda表达式里的`createbean()`,里面再调用`doCreateBean()`。前面讲过不多说,最终调用A的无参构造(pos_8),创建完之后发现A的B属性是null。
+
+
+
+ 5.在pos_9处的`addSingletonFactory()`来准备解决循环引用
+
+```java
+ protected void addSingletonFactory(String beanName, ObjectFactory> singletonFactory) {
+ Assert.notNull(singletonFactory, "Singleton factory must not be null");
+ synchronized (this.singletonObjects) {
+ if (!this.singletonObjects.containsKey(beanName)) { //当前对象如果没有在单例池中
+ this.singletonFactories.put(beanName, singletonFactory);
+ this.earlySingletonObjects.remove(beanName);
+ this.registeredSingletons.add(beanName);
+ }
+ }
+ }
+```
+
+
+
+
+
+6. 接着在pos_10处的`populateBean()`开始给属性赋值,这一步就是要把`B b`自动装配进来。主要是
+
+```java
+ protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
+ if (bw == null) {
+ if (mbd.hasPropertyValues()) {
+ throw new BeanCreationException(
+ mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
+ }
+ else {
+ // Skip property population phase for null instance.
+ return;
+ }
+ }
+
+ // @Autowired赋值也在这里(但是没做事)。可以中断初始化行为; 在属性赋值之前,后置处理器可以提前准备些东西 Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
+
+ if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
+ for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
+ if (!bp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
+ return;
+ }
+ }
+ } //以上的后置处理器可以中断以下的行为
+
+ PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
+
+ int resolvedAutowireMode = mbd.getResolvedAutowireMode();
+ if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
+ // ...
+ }
+
+ boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
+ boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
+
+ PropertyDescriptor[] filteredPds = null;
+ if (hasInstAwareBpps) {
+ if (pvs == null) {
+ pvs = mbd.getPropertyValues(); //xml中property标签指定的
+ } //使用后置处理器处理属性
+ for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
+ PropertyValues pvsToUse = bp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
+ if (pvsToUse == null) {
+ if (filteredPds == null) {
+ filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
+ }
+ pvsToUse = bp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
+ if (pvsToUse == null) {
+ return;
+ }
+ }
+ pvs = pvsToUse; //封装了当前bean的所有属性名和值,可以由后置处理器处理得到
+ }
+ }
+ // ...
+
+ if (pvs != null) { //把以前处理好的PropertyValues给bean里面设置一下。主要是上面步骤没有给bean里面设置的属性
+ applyPropertyValues(beanName, mbd, bw, pvs); //xml版的所有配置会来到这里给属性赋值
+ }
+ }
+```
+
+通过前面讲过的AutowiredAnnotationBeanPostProcessor来注入B,最后发现要调用setB方法给B赋值
+
+
+
+7. 继续走,发现要想获得B还是要调用getBean
+
+
+
+```java
+ public Object resolveCandidate(String beanName, Class> requiredType, BeanFactory beanFactory)
+ throws BeansException {
+
+ return beanFactory.getBean(beanName); //所有自动注入的属性都是beanFactory.getBean(beanName);的结果
+ }
+```
+
+
+
+然后图就是这样子
+
+
+
+
+
+8. B也是走这一套
+
+
+
+9. B为了获取A,还要再走一次getBean()流程,最终还是走到
+
+```java
+ //☆☆☆ pos_4
+ @Nullable //双检查锁
+ protected Object getSingleton(String beanName, boolean allowEarlyReference) {
+ //先检查单例缓存池,获取当前对象 Quick check for existing instance without full singleton lock
+ Object singletonObject = this.singletonObjects.get(beanName); //一级缓存
+ if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) { //如果当前bean正在创建过程中,而且缓存中没有则继续
+ singletonObject = this.earlySingletonObjects.get(beanName); //二级
+ if (singletonObject == null && allowEarlyReference) {
+ synchronized (this.singletonObjects) {
+ // Consistent creation of early reference within full singleton lock
+ singletonObject = this.singletonObjects.get(beanName);
+ if (singletonObject == null) {
+ singletonObject = this.earlySingletonObjects.get(beanName);
+ if (singletonObject == null) {
+ ObjectFactory> singletonFactory = this.singletonFactories.get(beanName); //三级
+ if (singletonFactory != null) {
+ singletonObject = singletonFactory.getObject();// 用那个lamda表达式拿对象
+ this.earlySingletonObjects.put(beanName, singletonObject);
+ this.singletonFactories.remove(beanName);
+ }
+ }
+ }
+ }
+ }
+ }
+ return singletonObject;
+ }
+```
+
+
+
+
+
+10.
+
+
+
+
+
+11. 得到A之后,B赋值结束。B进入初始化
+
+ ```java
+ populateBean(beanName, mbd, instanceWrapper); //给创建好的对象每个属性进行赋值,@Autowired发生在这里
+ exposedObject = initializeBean(beanName, exposedObject, mbd);//初始化bean
+ ```
+
+12. B初始化完之后,回到getSingleton,把自己放到单例池里
+
+
+
+```java
+protected void addSingleton(String beanName, Object singletonObject) {
+ synchronized (this.singletonObjects) {
+ this.singletonObjects.put(beanName, singletonObject);
+ this.singletonFactories.remove(beanName);
+ this.earlySingletonObjects.remove(beanName);
+ this.registeredSingletons.add(beanName);
+ }
+}
+```
+
+
+
+
+
+
+
+13. B全部结束之后回到A的流程,A赋值工作结束了,然后就开始A的初始化。初始化的过程中
+
+
+
+```java
+protected void addSingleton(String beanName, Object singletonObject) {
+ synchronized (this.singletonObjects) {
+ this.singletonObjects.put(beanName, singletonObject); //加到一级
+ this.singletonFactories.remove(beanName); //移除三级
+ this.earlySingletonObjects.remove(beanName); //移除二级
+ this.registeredSingletons.add(beanName);
+ }
+}
+```
+
+
+
+
+
+
+
+
+
+
+
+## 全部的流程图
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+