前言
接上一篇文章,我们之前讲了Spring源码中的主要的类,这篇文章就详细讲一下IOC容器创建的详细过程。让我们看看平常遇到的@Bean,@Component,@ComponentScan等等注解是怎么产生作用的。
首先统一一下用语:bean工厂==IOC容器。
正文
来看一个非常非常简单的IOC容器的创建
package org.study.jimmy;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.study.jimmy.bean.Apple;
import org.study.jimmy.config.Config;
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
Apple apple = context.getBean(Apple.class);
System.out.println(apple);
}
}
代码很简单,创建一个注解版的IOC容器,再根据Apple类型从IOC容器中获取bean实例。
接下来debug进源代码,首先进入IOC容器的构造函数。一共三行代码,这小小的3行代码背后却是整个IOC容器,就让我们分别进入这3行代码中瞧瞧。
一、this()方法的执行
public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
this();
register(componentClasses);
refresh();
}
进入this()方法,会实例化两个对象,望名知义,第一个AnnotatedBeanDefinitionReader类是被标注的bean定义读取器,另一个类ClassPathBeanDefinitionScanner是类路径下的bean定义扫描器。
public AnnotationConfigApplicationContext() {
this.reader = new AnnotatedBeanDefinitionReader(this);
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
注意:在本类的this()方法执行之前,会先执行父类的构造方法,我们在父类GenericApplicationContext的构造方法打一个端点,就会执行到这里。看!这里就充分表明了高级容器xxxApplicationContext持有基本容器xxxBeanFactory,而且这里的基本容器就是DefaultListableBeanFactory。
public GenericApplicationContext() {
this.beanFactory = new DefaultListableBeanFactory();
}
继续debug,回到上面的代码,让我们瞧瞧那2个Reader和Scanner干了啥。
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
// 截取主要代码
AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
}
这个AnnotatedBeanDefinitionReader的构造方法作用是向IOC容器中注册一些工具类,这些工具类会解析一些特殊注解的类(如@Configuration配置类)。
/**
* Register all relevant annotation post processors in the given registry.
*/
public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
BeanDefinitionRegistry registry, @Nullable Object source) {
// 只截取重要代码
// 如果IOC容器不包含这个名字的bean实例
if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
// 解析ConfigurationClassPostProcessor类的bean定义
RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
def.setSource(source);
// 注册解析后的bean定义到IOC容器中
beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
}
// 代码中以同样的方式注册了好几个bean定义
if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
}
// Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor.
if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
}
AnnotatedBeanDefinitionReader类的主要作用就是往IOC容器中注册一些工具类(ConfigurationClassPostProcessor、AutowiredAnnotationBeanPostProcessor等),有没有发现,这些工具类均实现了下面2个接口,这两个接口是干什么的呢?这是2个后置处理器,是为了实现bean生命周期管理的,如何实现呢?就是在IOC容器创建好后,bean开始实例化之前对BeanFactory进行一些处理。
上面说的是不是不太好理解?我们来画个图吧,这张图表明,IOC容器的创建可以分为4步,bean工场创建–bean定义注册–bean实例化–bean初始化,最后bean工场创建好就可以从中获取想要的bean实例了。Spring之所以强大,就强大在IOC容器创建过程中有很多的扩张点,这些扩展点基本上都是围绕以上4步来扩展的,比如bean工场创建后,容器中会加载一些内置的类(如解析@Configuration配置类的内置类);再比如bean实例化后会判断是否需要为当前对象创建代理(AOP的功能就是从这里实现的)。上面这个图中的两个接口的方法就是在IOC容器创建好后,bean实例化前执行。这里先混个眼熟,后面我们还会遇到这些后置处理器的。
再来看看ClassPathBeanDefinitionScanner这个类是做什么的,这个类的核心方法是doScan()方法,作用是扫描类路径下被@Component(@Controller、@Service等实质还是@Component)标注的Bean,并将BeanDefinition注册到IOC容器中。但是在this()方法中,ClassPathBeanDefinitionScanner并没有做太多事情,而是做了简单的配置。真正执行doScan()方式是在执行bean工厂后置处理器的时候,这里又出现了“后置处理器”。在学习Spring源码的时候,是绕不过“后置处理器”(PostProcessor)的,甚至可以说Spring源码的核心就是这些个后置处理器。
至此,this()方法就执行完了。
二、register()方法的执行
这个函数比较简单,就是读取到类的BeanDefinition,然后注册进IOC,之前一直说这个事情,下面就来看一下源码。
private <T> void doRegisterBean(Class<T> beanClass, @Nullable String name,
@Nullable Class<? extends Annotation>[] qualifiers, @Nullable Supplier<T> supplier,
@Nullable BeanDefinitionCustomizer[] customizers) {
// 得到bean的注解版BeanDefinition
AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(beanClass);
if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
return;
}
abd.setInstanceSupplier(supplier);
ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
abd.setScope(scopeMetadata.getScopeName());
// 给bean取一个名字,若不指定则取默认名字(类名首字母小写)
String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));
AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
if (qualifiers != null) {
for (Class<? extends Annotation> qualifier : qualifiers) {
if (Primary.class == qualifier) {
abd.setPrimary(true);
}
else if (Lazy.class == qualifier) {
abd.setLazyInit(true);
}
else {
abd.addQualifier(new AutowireCandidateQualifier(qualifier));
}
}
}
if (customizers != null) {
for (BeanDefinitionCustomizer customizer : customizers) {
customizer.customize(abd);
}
}
// 将beanName和BeanDefinition封装进BeanDefinitionHolder
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
// 注册进IOC容器
BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
}
继续追踪注册IOC容器的代码,会看到如系列一中所讲的,最终会走到普通容器DefaultListableBeanFactory里面注册bean定义信息的方法:registerBeanDefinition(),这个函数的核心就只有一行,往Map里面添加一个K-V对(beanName,beanDefinition)。
this.beanDefinitionMap.put(beanName, beanDefinition);
至此,我们将配置类也注册进了IOC容器,目前配置类还不起作用,要等到下面这个refresh()方法执行才能有效果。
三、refresh()方法执行
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
}
这个方法是重点,接下来我们对每一行方法都进行分析:
1、prepareRefresh()
这个方式比较简单,做了一些容器的属性初始化。
2、obtainFreshBeanFactory()
该方法的作用是告诉子类要刷新IOC容器,该方法中的refreshBeanFactory()方法是个抽象方法,被2个子类实现,如下图,这两个子类分别代表了XML版和注解版的IOC容器。按照你指定的容器类型去到相应类的代码中。
3、prepareBeanFactory(beanFactory)
该方法设置了一些bean工厂的属性,还添加了几个和系统相关的单例。
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());
}
4、postProcessBeanFactory(beanFactory);
该方法为空方法,留给子类去实现
5、invokeBeanFactoryPostProcessors(beanFactory)
该方法比较重要,这里就是第一个扩展点,从方法名就可以看出,这里是要执行BeanFactory的后置处理器类中的方法了。从前面的this()方法中我们看到,基本容器DefaultListableBeanFactory被创建好了,那么在bean工厂被创建好,bean实例化前,这里加入一个扩展点,可以对刚创建好的bean工厂进行一些改变,我们来看看源码做了什么。
该方法委托给了PostProcessorRegistrationDelegate工具类的静态方法invokeBeanFactoryPostProcessors()来执行后置处理器的方法。下面这一大段代码看着很长,其实很有条理:
5.1 首先找到bean工厂中实现了BeanDefinitionRegistryPostProcessor接口的类,然后从找到的类中按3个顺序(实现PriorityOrdered接口、实现Ordered接口、其他)执行BeanDefinitionRegistryPostProcessor接口中的postProcessBeanDefinitionRegistry()方法。
5.2 然后找到bean工厂中实现了BeanFactoryPostProcessor接口的类,然后从找到的类中按3个顺序(实现PriorityOrdered接口、实现Ordered接口、其他)执行BeanFactoryPostProcessor接口中的postProcessBeanFactory()方法。
代码可以一步一步进行调试,只贴出部分代码:
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
// Separate between BeanDefinitionRegistryPostProcessors that implement
// PriorityOrdered, Ordered, and the rest.
List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
// 从bean工厂取出实现了BeanDefinitionRegistryPostProcessor接口的bean名称
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
// 如果实现了PriorityOrdered接口
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
// getBean()方法是实例化对象用的
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
// 排序
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
// 执行后置处理器的postProcessBeanDefinitionRegistry()方法
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
举个例子,前面我们往IOC容器注册了配置类(@Configuration),也在this()阶段注册了一个内部的工具类ConfigurationClassPostProcessor,这个工具类就是用来解析配置类的。
至此,是不是有一点明白了所谓后置处理器的作用了呢?其实就是在IOC进行到某个阶段前后,对这个阶段可以进行一些扩展。
我们知道,配置类的主要功能是在容器启动时给IOC容器添加一系列组件的,其中@ComponentScan和@Bean注解使用最常见。我们再来看看这个后置处理器的接口类名称BeanDefinitionRegistryPostProcessor,顾名思义:就是注册bean定义的,再看看接口唯一的一个方法的名字:postProcessBeanDefinitionRegistry(),还是顾名思义就是注册bean定义的。我们进到这个后置处理器中看看,一路追踪代码我们可以看到,这个工具类就是在拿到所有的配置类,然后通过解析配置类,向IOC容器中添加bean定义。
6、registerBeanPostProcessors(beanFactory)
这个方法是注册BeanPostProcessor,BeanPostProcessor又是什么呢?这是个接口,也是后置处理器,也是bean生命周期管理的重要一环,这个接口里面的2个方法分别在bean初始化方法执行前后执行。同时,还有个比较重要的接口是InstantiationAwareBeanPostProcessor,这个接口里面的方法是在bean实例创建前后执行。注意:这里说的两个接口一个是初始化(初始化方法执行)前后,另一个是实例化(构造方法执行)前后。
这个方法同样还是委托给PostProcessorRegistrationDelegate类来注册后置处理器,实际上就是将BeanPostProcessor的子类对象添加到AbstractBeanFactory类的List属性,如下图:
/** BeanPostProcessors to apply. */
private final List<BeanPostProcessor> beanPostProcessors = new CopyOnWriteArrayList<>();
下面是具体的注册过程:
public static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
// 从IOC容器中得到BeanPostProcessor的所有子类型
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.
// 将不同优先级的BeanPostProcessor分开
List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
priorityOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else {
nonOrderedPostProcessorNames.add(ppName);
}
}
// First, register the BeanPostProcessors that implement PriorityOrdered.
// 首先往list中添加优先级最高的
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
// Next, register the BeanPostProcessors that implement Ordered.
// 其次往list中添加优先级次高的
List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
for (String ppName : orderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
orderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
sortPostProcessors(orderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, orderedPostProcessors);
// Now, register all regular BeanPostProcessors.
// 再往list中添加优先级低的
List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
for (String ppName : nonOrderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
nonOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
// Finally, re-register all internal BeanPostProcessors.
sortPostProcessors(internalPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, internalPostProcessors);
// Re-register post-processor for detecting inner beans as ApplicationListeners,
// moving it to the end of the processor chain (for picking up proxies etc).
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}
7、initMessageSource()
国际化信息
8、initApplicationEventMulticaster()
注册事件多路广播器SimpleApplicationEventMulticaster。
9、onRefresh()
空方法,由子类实现
10、registerListeners()
注册监听器
11、finishBeanFactoryInitialization(beanFactory)
该方法比较重要,作用是实例化剩余的(非懒加载)单实例。追踪代码,最终会执行到下面这个方法,该方法实际上是在DefaultListableBeanFactory类中执行的。
public void preInstantiateSingletons() throws BeansException {
...
// 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.
// 获取所有的bean名称
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()) {
// 工厂bean的创建方式
if (isFactoryBean(beanName)) {
Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
...
}
// 普通bean的创建方式
else {
// 真正实例化bean的方法
getBean(beanName);
}
}
}
// Trigger post-initialization callback for all applicable beans...
// 创建完bean后的回调方法,也是bean生命周期的重要一环
for (String beanName : beanNames) {
...
else {
// 真正的回调函数
smartSingleton.afterSingletonsInstantiated();
}
}
}
}
getBean()方法又调用了父类的doGetBean()方法
protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
final String beanName = transformedBeanName(name);
Object bean;
// Eagerly check singleton cache for manually registered singletons.
// 如果已经bean已经存在了,就直接返回
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
...
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
else {
...
// Check if bean definition exists in this factory.
// 检查一下父容器中是否存在
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// Not found -> check parent.
...
}
// 首先标记bean被创建了
if (!typeCheckOnly) {
markBeanAsCreated(beanName);
}
try {
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args);
// Guarantee initialization of beans that the current bean depends on.
// 如果bean实例有依赖的bean(@DependsOn注解),则需要先实例化依赖的bean。
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (String dep : dependsOn) {
...
registerDependentBean(dep, beanName);
getBean(dep);
}
}
// Create bean instance.
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, () -> {
try {
// 真正创建bean的函数,需要重点看看
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
...
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
else if (mbd.isPrototype()) {
...
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}
else {
...
bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
}
}
}
catch (BeansException ex) {
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
}
// Check if required type matches the type of the actual bean instance.
// 最后检查一下类型,无误则返回bean
if (requiredType != null && !requiredType.isInstance(bean)) {
...
}
return (T) bean;
}
来重点看看createBean()方法,需关注一下重点:
重点1:在bean实例化前执行所有BeanPostProcessor的postProcessBeforeInstantiation()方法,该方法返回一个目标对象的代理对象。
@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
...
try {
// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
// 重点1:在bean实例化前执行所有BeanPostProcessor的postProcessBeforeInstantiation()方法
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
return bean;
}
}
catch (Throwable ex) {
...
}
try {
// 真正创建bean实例
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
...
return beanInstance;
}
catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
...
}
catch (Throwable ex) {
...
}
}
再来看doCreateBean()方法,IOC容器创建最核心的3个方法都在这里了:
1、createBeanInstance
2、populateBean
3、initializeBean
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
throws BeanCreationException {
// Instantiate the bean.
BeanWrapper instanceWrapper = null;
...
if (instanceWrapper == null) {
instanceWrapper = createBeanInstance(beanName, mbd, args);
//到这里bean实例就被创建好了
}
// Allow post-processors to modify the merged bean definition.
synchronized (mbd.postProcessingLock) {
...
// 这里是一个重要的扩展点
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
mbd.postProcessed = true;
}
...
// Initialize the bean instance.
// 实例化后就该初始化了
Object exposedObject = bean;
try {
// 注入属性
populateBean(beanName, mbd, instanceWrapper);
// 执行初始化方法
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
catch (Throwable ex) {
...
}
if (earlySingletonExposure) {
...
}
return exposedObject;
}
1、以下几个是createBeanInstance()级辅助函数,该方法会选择用哪种方式来实例化bean,比如工厂方法、无参构造器等。我们来看无参构造器。
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
...
if (mbd.getFactoryMethodName() != null) {
return instantiateUsingFactoryMethod(beanName, mbd, args);
}
...
// No special handling: simply use no-arg constructor.
return instantiateBean(beanName, mbd);
}
来看无参构造器
protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
try {
...
beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
BeanWrapper bw = new BeanWrapperImpl(beanInstance);
initBeanWrapper(bw);
return bw;
}
catch (Throwable ex) {
...
}
}
最终会使用CGLIB的方式来创建bean实例
public static <T> T instantiateClass(Constructor<T> ctor, Object... args) throws BeanInstantiationException {
...
ReflectionUtils.makeAccessible(ctor);
...
return ctor.newInstance(argsWithDefaultValues);
}
2、populateBean(),若有属性配置则注入属性,读取bean的属性,并利用反射给属性注入值。
扩展点1:InstantiationAwareBeanPostProcessor类的postProcessAfterInstantiation()方法,在bean实例化后执行。
扩展点2:InstantiationAwareBeanPostProcessor类的postProcessProperties()方法,在bean属性赋值后执行
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
// state of the bean before properties are set. This can be used, for example,
// to support styles of field injection.
// 扩展点1
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
if (!ibp.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) {
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
// Add property values based on autowire by name if applicable.
if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}
// Add property values based on autowire by type if applicable.
if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mbd, bw, newPvs);
}
pvs = newPvs;
}
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
PropertyDescriptor[] filteredPds = null;
if (hasInstAwareBpps) {
if (pvs == null) {
pvs = mbd.getPropertyValues();
}
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
return;
}
}
pvs = pvsToUse;
}
}
}
if (needsDepCheck) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
checkDependencies(beanName, mbd, filteredPds, pvs);
}
if (pvs != null) {
applyPropertyValues(beanName, mbd, bw, pvs);
}
}
3、initializeBean()方法执行,该方法执行bean的初始化方法,并且在初始化方法执行前后有2个扩展点。分别是BeanPostProcessor类的postProcessBeforeInitialization()和postProcessAfterInitialization()方法。
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
...
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
//初始化之前执行后置处理器的方法
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
// 执行初始化方法
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
...
}
if (mbd == null || !mbd.isSynthetic()) {
// 初始化之后执行后置处理器的方法
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
至此,bean实例就创建好了。
12、finishRefresh()
最后一步,发布一系列事件。
总结
IOC容器的创建过程可以简单总结为:创建基本容器DefaultListableBeanFactory,读取用户配置的bean定义信息到基本容器中,实例化并初始化这些bean定义到容器,并且有一些后置处理器参与到bean的创建过程中。