目录

Spring源码 - Bean实例化整体流程

spring源码系列文章,示例代码的中文注释,均是 copy 自 https://gitee.com/wlizhi/spring-framework

链接中源码是作者从 github 下载,并以自身理解对核心流程及主要节点做了详细的中文注释。


1 常见的ApplicationContext实现类:

spring容器都是从构造一个ApplicationContext对象开始的,以下是spring中常见的ApplicationContext实现。

  • 容器:AbstractApplicationContext 抽象父类,核心(模板)方法 refresh()。
    • ClassPathXmlApplicationContext - XML方式启动。
    • AnnotationConfigWebApplicationContext - 注解方式启动,对局部代码进行测试时比较好用。
    • AnnotationConfigServletWebServerApplicationContext - SpringBoot启动默认使用的上下文类。

2 核心方法refresh() 。

在spring容器启动时,会调用到核心方法refrsh()。这个方法定义了spring容器初始化核心流程。包含创建beanFactory、XML解析、注解支持、后置处理器注册执行、BeanPostProcessor注册、Bean实例化等节点。

以下是spring中refresh()源码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
public abstract class AbstractApplicationContext extends DefaultResourceLoader
		implements ConfigurableApplicationContext {
    @Override
    public void refresh() throws BeansException, IllegalStateException {
        synchronized (this.startupShutdownMonitor) {
            // Prepare this context for refreshing.
            // 不太重要,预刷新,做一些准备工作。记录了启动时间戳,标记为活动,非关闭状态。
            prepareRefresh();
    
            /**
             * TODO 重点:解析xml配置文件,创建beanFactory,包装BeanDefinition
             */
            // Tell the subclass to refresh the internal bean factory.
            ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
    
            // Prepare the bean factory for use in this context.
            // 注册一些对事件、监听器等的支持
            prepareBeanFactory(beanFactory);
            
            // 钩子方法,BeanFactory创建后,对BeanFactory的自定义操作。
            // Allows post-processing of the bean factory in context subclasses.
            postProcessBeanFactory(beanFactory);

            // TODO 重点:这里调用了postProcessBeanDefinitionRegistry(registry);springboot中很多激活自动配置的注解都是通过这里导入的。
            // Invoke factory processors registered as beans in the context.
            invokeBeanFactoryPostProcessors(beanFactory);

            // TODO 重点:从beanFactory中获取所有的BeanPostProcessor,优先进行getBean操作,实例化
            // Register bean processors that intercept bean creation.
            registerBeanPostProcessors(beanFactory);

            // 国际化支持
            // Initialize message source for this context.
            initMessageSource();

            // 初始化ApplicationEventMulticaster。 如果上下文中未定义,则使用SimpleApplicationEventMulticaster。
            // Initialize event multicaster for this context.
            initApplicationEventMulticaster();

            // 钩子方法,springBoot中的嵌入式tomcat就是通过此方法实现的
            // Initialize other special beans in specific context subclasses.
            onRefresh();

            // 监听器注册
            // Check for listener beans and register them.
            registerListeners();

            // TODO 重点方法:完成容器中bean的实例化,及代理的生成等操作。
            // Instantiate all remaining (non-lazy-init) singletons.
            finishBeanFactoryInitialization(beanFactory);

            // 完成此上下文的刷新,调用LifecycleProcessor的onRefresh()方法并发布
            // Last step: publish corresponding event.
            finishRefresh();
            // ... 省略无关代码
        }
    }
}

3 Bean实例化入口,getBean()

bean实例化的入口是getBean()。对于单例Bean(实际开发中大多数都是单例),在初始化过程中,是从refresh()中,调用到finishBeanFactoryInitialization(),然后调用到preInstantiateSingletons()。

在preInstantiateSingletons()中(DefaultListableBeanFactory类中),调用到了getBean(),源码如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
    @Override
	public void preInstantiateSingletons() throws BeansException {
        // 容器中所有的beanName,循环、实例化
        // Iterate over a copy to allow for init methods which in turn register new bean definitions.
        // While this may not be part of the regular factory bootstrap, it does otherwise work fine.
        List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
    
        // 循环调用,进行实例化
        // Trigger initialization of all non-lazy singleton beans...
        for (String beanName : beanNames) {
            RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
            // 非抽象的、单例的、并且非懒加载的,才会在容器启动时就实例化。
            if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
                if (isFactoryBean(beanName)) {
                    Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
                    if (bean instanceof FactoryBean) {
                        final FactoryBean<?> factory = (FactoryBean<?>) bean;
                        boolean isEagerInit;
                        if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
                            isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>)
                                            ((SmartFactoryBean<?>) factory)::isEagerInit,
                                    getAccessControlContext());
                        }
                        else {
                            isEagerInit = (factory instanceof SmartFactoryBean &&
                                    ((SmartFactoryBean<?>) factory).isEagerInit());
                        }
                        if (isEagerInit) {
                            getBean(beanName);
                        }
                    }
                }
                else {
                    getBean(beanName);
                }
            }
        }
    }
}
注意
从以上源码中可以看到,在已经搜集好的BeanDefinition集合中,只有非抽象的、单例的、并且非懒加载的,才会在容器启动时就实例化。

4 实例化主流程

暂且忽略无关代码,仅关注单例情况下,spring容器启动过程中bean的实例化。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
    @SuppressWarnings("unchecked")
    protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
                              @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
        /*
          TODO 重要程度 5
            单例实例第一次创建bean入口,这里的getSingleton方法中,调用了参数中匿名对象的getObject()
            在bean创建完成后,将bean放入到一级缓存,并从二三级缓存中移除:addSingleton(beanName, singletonObject);
         */
        // Create bean instance.
        if (mbd.isSingleton()) {
            sharedInstance = getSingleton(beanName, () -> {
                try {
                    //创建Bean实例
                    return createBean(beanName, mbd, args);
                } catch (BeansException ex) {
                    // Explicitly remove instance from singleton cache: It might have been put there
                    // eagerly by the creation process, to allow for circular reference resolution.
                    // Also remove any beans that received a temporary reference to the bean.
                    destroySingleton(beanName);
                    throw ex;
                }
            });
            /*
            TODO 重要程度 5
                如果bean不是FactoryBean类型或者beanName以&开头,则直接返回。
                否则调用FactoryBean的getObject(),且将返回的bean替换为getObject()的返回值。
                FactoryBean接口很重要,具体应用场景见FactoryBean接口注释。
             */
            bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
        } 
    }
}

其中有三个关键的方法,分别是getSingleton()、函数接口(ObjectFactory)中的createBean()、以及最后调用的getObjectForBeanInstance()。

getSingleton()中调用到了匿名函数中的getObject(),这个getObject就是外围方法中的lambda表达式中的方法,这里面调用了createBean()。

来到createBean():

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
    @Override
	protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
			throws BeanCreationException {
        // ...省略无关代码
        // 这里如果满足条件,会调用 InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation()和
        // BeanPostProcessor.postProcessAfterInitialization(),直接返回。
        // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
        Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
        if (bean != null) {
            return bean;
        }
        // ...省略无关代码
        //创建Bean实例
        Object beanInstance = doCreateBean(beanName, mbdToUse, args);
        if (logger.isTraceEnabled()) {
            logger.trace("Finished creating instance of bean '" + beanName + "'");
        }
        return beanInstance;
	}
}

在createBean中,doCreateBean()是真正创建Bean实例的方法。在此之前,spring预留了一个扩展点,通过实现InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation()方法,可以通过BeanPostProcessor返回一个实例,这时候就不会再调用doCreateBean了。

InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation()的调用逻辑(源码中文注释中,详细描述了它的调用过程):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
    @Nullable
	protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
		Object bean = null;
		// 如果满足条件,会在这里通过InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation()进行实例化。
		// 如果此方法最终返回的值不为空,则会调用所有BeanPostProcessor的postProcessAfterInitialization(),
		// 标记是否已经提前实例化了bean,然后返回。
		if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
			// Make sure bean class is actually resolved at this point.
			if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
				Class<?> targetType = determineTargetType(beanName, mbd);
				if (targetType != null) {
					bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
					if (bean != null) {
						bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
					}
				}
			}
			mbd.beforeInstantiationResolved = (bean != null);
		}
		return bean;
	}
}

在doCreateBean中,经历了以下调用流程。

  1. createBeanInstance:创建bean实例,这里真正创建了bean的实例。
  2. applyMergedBeanDefinitionPostProcessors:这里是BeanPostProcessor的一个扩展点,添加了PostConstruct、PreDestroy、Autowired、Value、Inject注解的支持。官方注释是:将MergedBeanDefinitionPostProcessors应用于指定的bean定义,调用其{@code postProcessMergedBeanDefinition}方法。
  3. populateBean:完成了依赖注入。其原理是通过调用InstantiationAwareBeanPostProcessor.postProcessProperties()(spring5.1版本开始)、InstantiationAwareBeanPostProcessor.postProcessPropertyValues()(spring5.1版本之前)。也是一个BeanPostProcessor扩展点。
  4. initializeBean:初始化bean。bean的init方法、Aop、事务扩展操作就是在这里处理的。
  5. registerDisposableBeanIfNecessary。注册bean的销毁方法。

其中每一步都涉及到了spring中核心的一些扩展点,源码相对比较深。这里挑选节点流程的关键点代码。

doCreateBean()源码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
    protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
			throws BeanCreationException {

		// Instantiate the bean.
		BeanWrapper instanceWrapper = null;
		if (mbd.isSingleton()) {
 			instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
		}
		// 创建bean实例
		if (instanceWrapper == null) {
			instanceWrapper = createBeanInstance(beanName, mbd, args);
		}
		// 省略无关代码...

		// Allow post-processors to modify the merged bean definition.
		synchronized (mbd.postProcessingLock) {
			if (!mbd.postProcessed) {
                applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
				// 省略无关代码...
				mbd.postProcessed = true;
			}
		}

		// Eagerly cache singletons to be able to resolve circular references
		// even when triggered by lifecycle interfaces like BeanFactoryAware.
		boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
				isSingletonCurrentlyInCreation(beanName));
		if (earlySingletonExposure) {
			// 省略无关代码...
			addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
		}

		// Initialize the bean instance.
		Object exposedObject = bean;
		
        // 依赖注入,类似属性上带有@Autowired注解的,都会在这里进行依赖注入
        populateBean(beanName, mbd, instanceWrapper);
        // 初始化bean
        exposedObject = initializeBean(beanName, exposedObject, mbd);
	    // 省略无关代码...
        //注册bean的销毁方法
        registerDisposableBeanIfNecessary(beanName, bean, mbd);
		return exposedObject;
	}
}

5 创建实例,createBeanInstance

在创建bean实例中,主要经历了一下流程:

  1. 判断,只有public修饰的类,才可以被创建,否则直接抛出异常。
  2. 通过BeanDefinition中的回调,来创建Bean实例。
  3. 使用FactoryMethod来创建实例,factory-method标签属性,或者@bean注解。
  4. 重新创建相同的Bean。
  5. 通过构造函数注入参数。
  6. 使用无参构造函数。(这里是重点,大多数情况下,都是使用的无参构造。)

任何一个流程有结果,就会直接创建bean的实例,并返回。

从源码中可以清晰的看出以上结论:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
    protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
		// Make sure bean class is actually resolved at this point.
		Class<?> beanClass = resolveBeanClass(mbd, beanName);

		// 只有public修饰的class才可以被创建
		if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
			throw new BeanCreationException(mbd.getResourceDescription(), beanName,
					"Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
		}

		// 通过BeanDefinition中的回调,来创建bean实例。一般不会走到这个条件里。
		Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
		if (instanceSupplier != null) {
			return obtainFromSupplier(instanceSupplier, beanName);
		}

		// 使用FactoryMethod创建bean实例。factory-method标签属性,或者@Bean注解标注的方法,会从这里创建实例。
		if (mbd.getFactoryMethodName() != null) {
			return instantiateUsingFactoryMethod(beanName, mbd, args);
		}

		// 重新创建相同bean,会走到这里。
		// Shortcut when re-creating the same bean...
		boolean resolved = false;
		boolean autowireNecessary = false;
		if (args == null) {
			synchronized (mbd.constructorArgumentLock) {
				if (mbd.resolvedConstructorOrFactoryMethod != null) {
					resolved = true;
					autowireNecessary = mbd.constructorArgumentsResolved;
				}
			}
		}
		if (resolved) {
			if (autowireNecessary) {
				return autowireConstructor(beanName, mbd, null, null);
			}
			else {
				return instantiateBean(beanName, mbd);
			}
		}

		// 判断是否是通过构造函数注入参数,如果是,则通过@Autowired标注的构造函数实例化。
		// Candidate constructors for autowiring?
		Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
		if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
				mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
			return autowireConstructor(beanName, mbd, ctors, args);
		}

		// 默认构造的首选函数
		// Preferred constructors for default construction?
		ctors = mbd.getPreferredConstructors();
		if (ctors != null) {
			return autowireConstructor(beanName, mbd, ctors, null);
		}

		// 使用无参构造实例化bean,实际大多数bean的实例化,都是走的这个方法。
		// No special handling: simply use no-arg constructor.
		return instantiateBean(beanName, mbd);
	}
}

记录一下无参构造函数创建实例的过程:

  1. getInstantiationStrategy():获取bean的实例化策略对象,默认使用的CglibSubclassingInstantiationStrategy。
  2. instantiate(mbd, beanName, parent):实例化bean。
  3. instantiate -> BeanUtils.instantiateClass() -> ctor.newInstance()。反射调用无参构造函数,创建对象。

源码如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class SimpleInstantiationStrategy implements InstantiationStrategy {
    // 第一步
    @Override
	public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
		// Don't override the class with CGLIB if no overrides.
		if (!bd.hasMethodOverrides()) {
			// 省略无关代码...
            // 获取无参构造函数
            constructorToUse = clazz.getDeclaredConstructor();
            bd.resolvedConstructorOrFactoryMethod = constructorToUse;
			// 省略无关代码...
			// TODO 实例化bean
			return BeanUtils.instantiateClass(constructorToUse);
		} else {
			// Must generate CGLIB subclass.
			return instantiateWithMethodInjection(bd, beanName, owner);
		}
	}
}
public abstract class BeanUtils {
    // 第二步
    public static <T> T instantiateClass(Constructor<T> ctor, Object... args) throws BeanInstantiationException {
		Assert.notNull(ctor, "Constructor must not be null");
        // 设置构造函数setAccessible=true
        // newInstance:反射调用构造函数,创建bean对象。
        ReflectionUtils.makeAccessible(ctor);
        return (KotlinDetector.isKotlinReflectPresent() && KotlinDetector.isKotlinType(ctor.getDeclaringClass()) ?
                KotlinDelegate.instantiateClass(ctor, args) : ctor.newInstance(args));
		// 省略无关代码...
	}
}

源码中最后一行 ctor.newInstance(args) 创建了bean实例。然后逐层向上返回。

6 注解支持,applyMergedBeanDefinitionPostProcessors

这里执行了MergedBeanDefinitionPostProcessor.postProcessMergedBeanDefinition()方法。spring会加载在之前的流程中注册的MergedBeanDefinitionPostProcessor(BeanPostProcessor的子接口),并对其进行调用。比较典型的两个类,完成了@Autowried、@Value、@Injected、@PostConstruct、@PreDestroy等注解的支持

调用入口源码如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
		for (BeanPostProcessor bp : getBeanPostProcessors()) {
			if (bp instanceof MergedBeanDefinitionPostProcessor) {
				MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
				bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
			}
		}
	}
}

两个比较典型的实现:AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor

6.1 AutowiredAnnotationBeanPostProcessor

AutowiredAnnotationBeanPostProcessor中存储了需要@Autowired注入的一些信息映射。

构造函数中添加了对应注解的支持,postProcessMergedBeanDefinition()中查找带有Autowired注解的成员的属性信息信息,并将搜集结果封装缓存起来。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter
		implements MergedBeanDefinitionPostProcessor, PriorityOrdered, BeanFactoryAware {
    /**
	 * 在依赖注入之前,调用此方法搜集需要依赖注入的类的信息,并封装成InjectionMetadata对象,缓存到当前BeanPostProcessor实例中。
	 *
	 * @param beanDefinition the merged bean definition for the bean
	 * @param beanType       the actual type of the managed bean instance
	 * @param beanName       the name of the bean
	 */
	@Override
	public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
		// 查找带有Autowired注解的成员的属性信息信息。
		InjectionMetadata metadata = findAutowiringMetadata(beanName, beanType, null);
		metadata.checkConfigMembers(beanDefinition);
	}
}

此类完成了对@AutoWried、@Value、@Injected注解的支持。

执行buildAutowiringMetadata方法,完成的注解支持,之后会把结果缓存到injectionMetadataCache变量中。

构建元数据的过程:

  1. 循环目标Class的所有字段,查找@Autowired注解。如果查找到,将注解属性封装成AutowiredFieldElement,并封装到一个list中。
  2. 循环目标Class的所有方法,查找@Autowired注解,如果找到,将注解属性封装成AutowiredMethodElement,并封装到一个list中。
  3. 将以上两个步骤得到的结果,封装为InjectionMetadata,返回。即InjectionMetadata中包含了需要@Autowired的字段和方法。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter
		implements MergedBeanDefinitionPostProcessor, PriorityOrdered, BeanFactoryAware {
    // 无参构造函数中添加了对应注解的支持
    public AutowiredAnnotationBeanPostProcessor() {
		// 初始化autowiredAnnotationTypes,这里添加了Autowired Value Inject注解的支持
		this.autowiredAnnotationTypes.add(Autowired.class);
		this.autowiredAnnotationTypes.add(Value.class);
		try {
			this.autowiredAnnotationTypes.add((Class<? extends Annotation>)
					ClassUtils.forName("javax.inject.Inject", AutowiredAnnotationBeanPostProcessor.class.getClassLoader()));
			logger.trace("JSR-330 'javax.inject.Inject' annotation found and supported for autowiring");
		} catch (ClassNotFoundException ex) {
			// JSR-330 API not available:simply skip.
		}
	}

    private InjectionMetadata buildAutowiringMetadata(final Class<?> clazz) {
		List<InjectionMetadata.InjectedElement> elements = new ArrayList<>();
		Class<?> targetClass = clazz;

		do {
			final List<InjectionMetadata.InjectedElement> currElements = new ArrayList<>();

			// 循环所有的字段,并以此字段为参数,执行回调。
			ReflectionUtils.doWithLocalFields(targetClass, field -> {
				// 查找当前带有autowiredAnnotationTypes中支持的注解的字段。
				AnnotationAttributes ann = findAutowiredAnnotation(field);
				if (ann != null) {
					if (Modifier.isStatic(field.getModifiers())) {
						if (logger.isInfoEnabled()) {
							logger.info("Autowired annotation is not supported on static fields: " + field);
						}
						return;
					}
					boolean required = determineRequiredStatus(ann);
					currElements.add(new AutowiredFieldElement(field, required));
				}
			});

			// 循环所有的方法,并以此方法为参数,执行回调。
			ReflectionUtils.doWithLocalMethods(targetClass, method -> {
				Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
				if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
					return;
				}
				// 查找当前带有autowiredAnnotationTypes中支持的注解的方法。
				AnnotationAttributes ann = findAutowiredAnnotation(bridgedMethod);
				if (ann != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
					if (Modifier.isStatic(method.getModifiers())) {
						if (logger.isInfoEnabled()) {
							logger.info("Autowired annotation is not supported on static methods: " + method);
						}
						return;
					}
					if (method.getParameterCount() == 0) {
						if (logger.isInfoEnabled()) {
							logger.info("Autowired annotation should only be used on methods with parameters: " +
									method);
						}
					}
					boolean required = determineRequiredStatus(ann);
					PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
					currElements.add(new AutowiredMethodElement(method, required, pd));
				}
			});

			elements.addAll(0, currElements);
			targetClass = targetClass.getSuperclass();
		}
		while (targetClass != null && targetClass != Object.class);

		return new InjectionMetadata(clazz, elements);
	}

    @Nullable
	private AnnotationAttributes findAutowiredAnnotation(AccessibleObject ao) {
		if (ao.getAnnotations().length > 0) {  // autowiring annotations have to be local
            // autowiredAnnotationTypes中的注解值,是在无参构造函数中设置的。
			for (Class<? extends Annotation> type : this.autowiredAnnotationTypes) {
				AnnotationAttributes attributes = AnnotatedElementUtils.getMergedAnnotationAttributes(ao, type);
				if (attributes != null) {
					return attributes;
				}
			}
		}
		return null;
	}
}
注意
  • 构造函数中注入了对注解的支持,将其设置到了autowiredAnnotationTypes成员变量。在findAutowiredAnnotation()方法中。(上面源码中有体现

  • 查找匹配字段、方法上的注解时,用的就是autowiredAnnotationTypes变量。

  • 其中在findAutowiredAnnotation()方法中的参数AccessibleObject是Constructor、Field、Method的超类。

其中有几个关键封装数据的类。

  1. InjectionMetadata 用于管理注入元数据
    • targetClass 目标类的Class对象
    • injectedElements 需要注入的元素
    • checkedElements 系统内置的元素会放到这里面,因为是一个Set集合,constains方法效率比较高,用于校验是否包含某个元素
  2. InjectedElement 注入元素,它是一个抽象类,包含了注入字段、方法、LookupMethod、@Resource注解标注的字段等等注入元素类的抽象。这里列举几个比较关键的。
    1. AutowiredFieldElement -> 表示带@Autowired注解的字段注入信息。
      • required 是否必须
      • cached
      • cachedFieldValue 见名知意,缓存的字段值
    2. AutowiredMethodElement 表示带有@Autowired注解的方法注入信息。
      • required 是否必须
      • cached
      • cachedMethodArguments 缓存的方法参数值
    3. ResourceElement 表示有关带注释的字段或setter方法的注入信息的类,支持@Resource注解。
      • lazyLookup 懒加载,@Lazy注解信息的封装

6.2 CommonAnnotationBeanPostProcessor

CommonAnnotationBeanPostProcessor是InitDestroyAnnotationBeanPostProcessor的子类,也是一个BeanPostProcessor。设置了@PostConstruct、@PreDestroy、@Resource注解的支持。

注意
  • 两个比较重要的成员变量(初始化、销毁方法)是在InitDestroyAnnotationBeanPostProcessor定义的。
  • @PostConstruct、@PreDestroy注解支持是在CommonAnnotationBeanPostProcessor的无参构造函数中设置的。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
public class InitDestroyAnnotationBeanPostProcessor
		implements DestructionAwareBeanPostProcessor, MergedBeanDefinitionPostProcessor, PriorityOrdered, Serializable {
	@Nullable
	private Class<? extends Annotation> initAnnotationType;

	@Nullable
	private Class<? extends Annotation> destroyAnnotationType;
}

public class CommonAnnotationBeanPostProcessor extends InitDestroyAnnotationBeanPostProcessor
		implements InstantiationAwareBeanPostProcessor, BeanFactoryAware, Serializable {

    public CommonAnnotationBeanPostProcessor() {
		// 这里设置了PostConstruct、PreDestroy注解的支持。
		setOrder(Ordered.LOWEST_PRECEDENCE);
		setInitAnnotationType(PostConstruct.class);
		setDestroyAnnotationType(PreDestroy.class);
		ignoreResourceType("javax.xml.ws.WebServiceContext");
	}
}

搜集支持的元素并封装的流程:

  1. 先执行父类的搜集逻辑,这里设置了@PostConstruct、@PreDestroy注解的支持。
  2. 执行本类中的搜集逻辑,这里设置了@Resource注解的支持。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public class CommonAnnotationBeanPostProcessor extends InitDestroyAnnotationBeanPostProcessor
		implements InstantiationAwareBeanPostProcessor, BeanFactoryAware, Serializable {
    @Override
	public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
		// 先调用父类的方法,查找支持的元素,进行封装
		super.postProcessMergedBeanDefinition(beanDefinition, beanType, beanName);
		// 在调用本类中的方法,也是查找支持的元素,进行封装
		InjectionMetadata metadata = findResourceMetadata(beanName, beanType, null);
		metadata.checkConfigMembers(beanDefinition);
	}
}

在真正执行搜集注解逻辑之前,有一个锁的使用方式。父类和子类此方法中都有体现。先不加锁获取,如果为空,再加锁,尝试获取,如果加锁下获取还是空,则执行搜集逻辑,搜集完之后会放入缓存。缓存的map是非线程安全的。

如果我们存储一组数据,这组数据只需要存储一次,后面全部都是get操作,那么就可以使用这种非线程安全的集合(非线程安全的集合的get操作性能远高于线程安全集合)。在存储的时候,以先重试,再加锁的方式进行处理。更多关于线程安全的问题,在并发编程的知识模块里记录。

这里列举一个父类中的方法:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class InitDestroyAnnotationBeanPostProcessor
		implements DestructionAwareBeanPostProcessor, MergedBeanDefinitionPostProcessor, PriorityOrdered, Serializable {

    private LifecycleMetadata findLifecycleMetadata(Class<?> clazz) {
		if (this.lifecycleMetadataCache == null) {
			// Happens after deserialization, during destruction...
			return buildLifecycleMetadata(clazz);
		}
		// Quick check on the concurrent map first, with minimal locking.
		LifecycleMetadata metadata = this.lifecycleMetadataCache.get(clazz);
		if (metadata == null) {
			synchronized (this.lifecycleMetadataCache) {
				metadata = this.lifecycleMetadataCache.get(clazz);
				if (metadata == null) {
					// 上面代码是缓存,这里加锁的技巧,先无锁尝试,尝试失败再加锁。
					// 细节:加锁中需要再次尝试获取一次。
					metadata = buildLifecycleMetadata(clazz);
					this.lifecycleMetadataCache.put(clazz, metadata);
				}
				return metadata;
			}
		}
		return metadata;
	}
}

InitDestroyAnnotationBeanPostProcessor中搜集初始化、销毁方法的逻辑:根据成员变量(赋值的逻辑前文中有)initAnnotationType、destroyAnnotationType的类型,循环判断方法中是否有对应注解,有就缓存到对应集合中。遍历完所有方法之后将最终的结果封装成LifecycleMetadata

代码如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public class InitDestroyAnnotationBeanPostProcessor
		implements DestructionAwareBeanPostProcessor, MergedBeanDefinitionPostProcessor, PriorityOrdered, Serializable {

	private LifecycleMetadata buildLifecycleMetadata(final Class<?> clazz) {
		List<LifecycleElement> initMethods = new ArrayList<>();
		List<LifecycleElement> destroyMethods = new ArrayList<>();
		Class<?> targetClass = clazz;

		do {
			final List<LifecycleElement> currInitMethods = new ArrayList<>();
			final List<LifecycleElement> currDestroyMethods = new ArrayList<>();
			// 循环遍历所有的方法,查找初始化、销毁方法,如果查找到,就封装为LifecycleMetadata返回。
			ReflectionUtils.doWithLocalMethods(targetClass, method -> {
				if (this.initAnnotationType != null && method.isAnnotationPresent(this.initAnnotationType)) {
					LifecycleElement element = new LifecycleElement(method);
					currInitMethods.add(element);
					if (logger.isTraceEnabled()) {
						logger.trace("Found init method on class [" + clazz.getName() + "]: " + method);
					}
				}
				if (this.destroyAnnotationType != null && method.isAnnotationPresent(this.destroyAnnotationType)) {
					currDestroyMethods.add(new LifecycleElement(method));
					if (logger.isTraceEnabled()) {
						logger.trace("Found destroy method on class [" + clazz.getName() + "]: " + method);
					}
				}
			});

			// 添加初始化、销毁方法
			initMethods.addAll(0, currInitMethods);
			destroyMethods.addAll(currDestroyMethods);
			targetClass = targetClass.getSuperclass();
		}
		while (targetClass != null && targetClass != Object.class);

		// 将上面步骤搜集到的初始化、销毁方法封装起来返回。
		return new LifecycleMetadata(clazz, initMethods, destroyMethods);
	}
}

CommonAnnotationBeanPostProcessor中的搜集方法逻辑:

  1. 搜集带有@Resource注解的字段,封装成ResourceElement,最后封装到InjectionMetadata。
  2. 搜集带有@Resource注解的方法,封装成ResourceElement,最后封装到InjectionMetadata。

这个方法中也有两个其他支持(webservice、ejb),不常用,这里不列举。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public class CommonAnnotationBeanPostProcessor extends InitDestroyAnnotationBeanPostProcessor
		implements InstantiationAwareBeanPostProcessor, BeanFactoryAware, Serializable {

	private InjectionMetadata buildResourceMetadata(final Class<?> clazz) {
		List<InjectionMetadata.InjectedElement> elements = new ArrayList<>();
		Class<?> targetClass = clazz;

		do {
			final List<InjectionMetadata.InjectedElement> currElements = new ArrayList<>();

			// 查找带有@Resource的字段,有的话就封装到InjectedElement中。
			ReflectionUtils.doWithLocalFields(targetClass, field -> {
                // 省略无关代码...
				if (field.isAnnotationPresent(Resource.class)) {
					// 省略无关代码...
					if (!this.ignoredResourceTypes.contains(field.getType().getName())) {
						currElements.add(new ResourceElement(field, field, null));
					}
				}
			});

			// 查找@Resource注解的方法,查找到就封装到InjectedElement
			ReflectionUtils.doWithLocalMethods(targetClass, method -> {
				Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
				if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
					return;
				}
				if (bridgedMethod.isAnnotationPresent(Resource.class)) {
                    // 省略无关代码...
                    if (!this.ignoredResourceTypes.contains(paramTypes[0].getName())) {
                        PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
                        currElements.add(new ResourceElement(method, bridgedMethod, pd));
                    }
				}
			});

			elements.addAll(0, currElements);
			targetClass = targetClass.getSuperclass();
		}
		while (targetClass != null && targetClass != Object.class);

		return new InjectionMetadata(clazz, elements);
	}
}

几个关键的封装数据的类:

  • LookupElement 表示有关带注释的字段或setter方法的一般注入信息的类,支持@Resource和相关注释。
    • name 成员变量
    • isDefaultName 成员变量
    • lookupType 成员变量
    • mappedName 成员变量
  • ResourceElement LookupElement的子类。对Resource注解信息的封装。
    • lazyLookup 成员变量
  • LifecycleElement 表示有关带注释方法的注入信息的类,支持初始化、销毁方法。
    • method 成员变量
    • identifier 成员变量

7 依赖注入,populateBean

populateBean的作用是完成bean属性的依赖注入。

  1. 依赖注入之前,如果BeanDefinition是合成的,有InstantiationAwareBeanPostProcessor实例存在于ioc容器,那么将会执行容器中所有InstantiationAwareBeanPostProcessor.postProcessAfterInstantiation(),如果有一个方法返回false,则直接中断并返回。依赖注入不再进行。(它的用途暂时未知,如果这里返回false导致了一些问题,那么排查起来也是比较困难的,因为它没有任何提示信息输出
  2. 通过调用InstantiationAwareBeanPostProcessor.postProcessProperties()完成属性的依赖注入(spring5.1之前的版本调用的postProcessPropertyValues())。

由于是遍历容器中注册的BeanPostProcessor,找出是InstantiationAwareBeanPostProcessor类型的,这里不同的注入方式会有不同的实现类。与前文中说明的搜集依赖注入有关注解的方法是一样的,实现类也是同一个。遍历过程中会一个个的调用。由于这些BeanPostProcessor中在前面流程中已经缓存了需要依赖注入的内容。这里就可以根据缓存的内容进行获取,依次设置值到对应属性中了。

这里列举几个常见的注入流程

7.1 AutowiredFieldElement

它是对@Autowired标注在字段上的注入支持。

在前文中postProcessMergedBeanDefinition流程节点,添加@Autowired注解支持的时候,就把对应数据放入到了缓存中,成员变量injectionMetadataCache就是对应的缓存。

首先会调用findAutowiringMetadata()方法,获取元数据,这里直接从缓存injectionMetadataCache中拿的。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter
		implements MergedBeanDefinitionPostProcessor, PriorityOrdered, BeanFactoryAware {
    // 这两个成员变量中,在前面执行postProcessMergedBeanDefinition时,已经缓存了需要注入的元数据。
	private final Map<String, InjectionMetadata> injectionMetadataCache = new ConcurrentHashMap<>(256);
    @Override
	public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
		// 找到Autowiring注解标注的属性和方法,并封装为InjectionMetadata返回。
		InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
        // TODO 依赖注入的具体逻辑,重点看
		metadata.inject(bean, beanName, pvs);
		// 省略无关代码...
		return pvs;
	}
}

来到inject()方法,可以看到,遍历InjectionMetadata中缓存的injectedElements,然后执行每一个InjectedElement的inject()方法,这里就是@Autowired注入的核心逻辑:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter
		implements MergedBeanDefinitionPostProcessor, PriorityOrdered, BeanFactoryAware {
    public void inject(Object target, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
		Collection<InjectedElement> checkedElements = this.checkedElements;
		Collection<InjectedElement> elementsToIterate =
				(checkedElements != null ? checkedElements : this.injectedElements);
		if (!elementsToIterate.isEmpty()) {
			for (InjectedElement element : elementsToIterate) {
				// 执行依赖注入
				element.inject(target, beanName, pvs);
			}
		}
	}
}

从前文中已经知道,@Autowired的注解搜集,把字段和方法分成了两类来进行封装,分别是:AutowiredFieldElement、AutowiredMethodElement。

先来到AutowiredFieldElement的inject()方法:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
private class AutowiredFieldElement extends InjectionMetadata.InjectedElement {
    @Override
    protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
        // 字段的自动注入
        Field field = (Field) this.member;
        Object value;
        if (this.cached) {
            value = resolvedCachedArgument(beanName, this.cachedFieldValue);
        } else {
            DependencyDescriptor desc = new DependencyDescriptor(field, this.required);
            desc.setContainingClass(bean.getClass());
            Set<String> autowiredBeanNames = new LinkedHashSet<>(1);
            Assert.state(beanFactory != null, "No BeanFactory available");
            TypeConverter typeConverter = beanFactory.getTypeConverter();
            try {
                // 处理依赖项
                value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);
            } catch (BeansException ex) {
                throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(field), ex);
            }
            // 省略无关代码...
        }
        // 执行字段赋值逻辑。
        if (value != null) {
            ReflectionUtils.makeAccessible(field);
            field.set(bean, value);
        }
    }
}

获取依赖对象的方法调用链:
|-> resolveDependency
|-|-> doResolveDependency
|-|-|-> findAutowireCandidates
|-|-|-|-> addCandidateEntry
|-|-|-|-|-> descriptor.resolveCandidate
|-|-|-|-|-|-> beanFactory.getBean

最终还是调用到了getBean()方法。也就是经过一系列的处理,最终调用getBean()方法,获取到依赖的对象实例,返回,赋值。从上面代码可以看到,最后使用反射field.set()进行字段赋值。

7.2 AutowiredMethodElement

它是对@Autowired标注在方法上的注入支持。

通过方法@Autowired注入的流程是:先获取参数列表中依赖的实例对象,最终一定是会调用到getBean()方法。然后通过反射调用对应方法。

来到AutowiredMethodElement.inject()方法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
private class AutowiredMethodElement extends InjectionMetadata.InjectedElement {
    @Override
    protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
        if (checkPropertySkipping(pvs)) {
            return;
        }
        Method method = (Method) this.member;
        Object[] arguments;
        if (this.cached) {
            // Shortcut for avoiding synchronization...
            arguments = resolveCachedArguments(beanName);
        } else {
            Class<?>[] paramTypes = method.getParameterTypes();
            arguments = new Object[paramTypes.length];
            DependencyDescriptor[] descriptors = new DependencyDescriptor[paramTypes.length];
            Set<String> autowiredBeans = new LinkedHashSet<>(paramTypes.length);
            Assert.state(beanFactory != null, "No BeanFactory available");
            TypeConverter typeConverter = beanFactory.getTypeConverter();
            for (int i = 0; i < arguments.length; i++) {
                MethodParameter methodParam = new MethodParameter(method, i);
                DependencyDescriptor currDesc = new DependencyDescriptor(methodParam, this.required);
                currDesc.setContainingClass(bean.getClass());
                descriptors[i] = currDesc;
                try {
                    // 获取参数中依赖的对象
                    Object arg = beanFactory.resolveDependency(currDesc, beanName, autowiredBeans, typeConverter);
                    if (arg == null && !this.required) {
                        arguments = null;
                        break;
                    }
                    arguments[i] = arg;
                } catch (BeansException ex) {
                    throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(methodParam), ex);
                }
            }
           // 省略无关代码...
        }
        if (arguments != null) {
            try {
                // 反射调用
                ReflectionUtils.makeAccessible(method);
                method.invoke(bean, arguments);
            } catch (InvocationTargetException ex) {
                throw ex.getTargetException();
            }
        }
    }
}

获取依赖对象的方法调用链:
|-> resolveDependency
|-|-> doResolveDependency
|-|-|-> findAutowireCandidates
|-|-|-|-> addCandidateEntry
|-|-|-|-|-> descriptor.resolveCandidate
|-|-|-|-|-|-> beanFactory.getBean

仔细看一下,其实获取依赖对象本身,是和使用字段注入的获取方式一样的,调用的方法没有任何变化。不同之处在于外围方法,字段注入时只获取一个实例,方法则可能是多个实例,是一个数组,所以方法获取依赖属性时,以遍历的方式去执行以上流程的。

7.3 ResourceElement

它是对@Resource注解标注在字段/方法上的注入支持。

与上面流程一样,来到inject()方法,这里调用到了父类InjectedElement的inject()方法:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public abstract static class InjectedElement {
    protected void inject(Object target, @Nullable String requestingBeanName, @Nullable PropertyValues pvs)
            throws Throwable {

        if (this.isField) {
            Field field = (Field) this.member;
            ReflectionUtils.makeAccessible(field);
            // 字段赋值 关键点看getResourceToInject
            field.set(target, getResourceToInject(target, requestingBeanName));
        }
        else {
            if (checkPropertySkipping(pvs)) {
                return;
            }
            try {
                Method method = (Method) this.member;
                ReflectionUtils.makeAccessible(method);
                // 方法赋值 关键点看getResourceToInject
                method.invoke(target, getResourceToInject(target, requestingBeanName));
            }
            catch (InvocationTargetException ex) {
                throw ex.getTargetException();
            }
        }
    }

    @Override
    protected Object getResourceToInject(Object target, @Nullable String requestingBeanName) {
        return (this.lazyLookup ? buildLazyResourceProxy(this, requestingBeanName) :
                getResource(this, requestingBeanName));
    }
}

获取依赖对象的方法调用链:
|-> getResourceToInject
|-|-> getResource
|-|-|-> autowireResource
|-|-|-|-> factory.getBean

8 AOP、事务支持,initializeBean

外围方法节点:

  1. postProcessBeforeInitialization() bean实例化之后,初始化方法执行之前调用。
  2. invokeInitMethods() bean的初始化方法,@PostContructor注解的方法、或者配置文件配置的。
  3. postProcessAfterInitialization() bean实例化之后,初始化方法执行之后调用,也是AOP的入口。事务的入口不在这,但跟它有关,事务的Advisor对象是在这里填充到AOP的执行链的。

源码如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
    protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
		if (System.getSecurityManager() != null) {
			AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
				invokeAwareMethods(beanName, bean);
				return null;
			}, getAccessControlContext());
		}
		else {
			invokeAwareMethods(beanName, bean);
		}

		Object wrappedBean = bean;
		if (mbd == null || !mbd.isSynthetic()) {
			// BeanPostProcessor.postProcessBeforeInitialization()
			// 顾名思义,在bean实例创建完成并依赖注入后,初始化方法执行之前,会执行此方法。
			// AOP的BeanPostProcessor也实现了这个方法,只是直接返回了原始对象。真正入口在后置处理。
			wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
		}

		try {
			// 执行初始化方法,InitializingBean实例的afterPropertiesSet,或者init-method或者@PostConstructor标注的方法
			invokeInitMethods(beanName, wrappedBean, mbd);
		}
		catch (Throwable ex) {
			throw new BeanCreationException(
					(mbd != null ? mbd.getResourceDescription() : null),
					beanName, "Invocation of init method failed", ex);
		}
		if (mbd == null || !mbd.isSynthetic()) {
			// BeanPostProcessor.postProcessAfterInitialization()
			// 顾名思义,在bean实例创建完成并依赖注入后,初始化方法执行之后,会执行此方法。
			// AOP的入口,通过AspectJAwareAdvisorAutoProxyCreator生成代理对象
			wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
		}

		return wrappedBean;
	}
}
注意
由于篇幅原因,这里只做initializeBean()方法的执行流程描述。关于SpringAop执行链的封装和动态代理生成以及执行原理,事务的支持、事务的七种传播属性实现原理及其表现形式。在别的文章中分析。

9 临终方法注册,registerDisposableBeanIfNecessary

beanFactory中有一个成员变量disposableBeans,这是一个map集合,里面就封装了bean销毁前需要调用的对象映射。键时beanName,值是DisposableBeanAdapter

DisposableBeanAdapter中封装了destroyMethod以及List,没错,是一个list列表。因为可以设置多个销毁方法,且设置的方式也是有很多种,可以实现DisposableBean,或者注解方式,或者名称为close的无参数公共方法

ban的销毁前调用方法的注册,相对简单,这里贴两段代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {

    protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
		AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
		// BeanDefinition非多例,并且需要销毁。
		if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {
			if (mbd.isSingleton()) {
				// Register a DisposableBean implementation that performs all destruction
				// work for the given bean: DestructionAwareBeanPostProcessors,
				// DisposableBean interface, custom destroy method.
				// 注册bean的销毁前调用的方法
				registerDisposableBean(beanName,
						new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
			} else {
				// A bean with a custom scope...
				Scope scope = this.scopes.get(mbd.getScope());
				if (scope == null) {
					throw new IllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'");
				}
				scope.registerDestructionCallback(beanName,
						new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
			}
		}
	}
}
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
    public void registerDisposableBean(String beanName, DisposableBean bean) {
		synchronized (this.disposableBeans) {
			this.disposableBeans.put(beanName, bean);
		}
	}
}