通过这段代码作为分析的入口。以下分析都基于该示例,完整代码见:https://github.com/abelzha/spring-framework
public class InitMain {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfigInit.class);
System.out.println(Arrays.asList(context.getBeanFactory().getBeanDefinitionNames()).toString().replaceAll(",", "\n"));
Person person = context.getBean(Person.class);
System.out.println(person.getName());
context.close();
}
}
1. IOC容器启动—Bean的初始化顺序
在Spring启动的时候会先创建容器、进行Bean的初始化。
1、根据配置类,创建容器,完成添加内置类的beanDefinitionMap
1、创建容器(AnnotationConfigApplicationContext)
容器的中的bean工厂:DefaultListableBeanFactory
2、初始配置信息设置,填充各种map、set.如下图所示
现在我们只关注一个map,它就是beanDefinitionMap。
将内置类的beanDefinition放入beanDefinitionMap,以下是该示例的默认添加的5个内置类
1 name:org.springframework.context.annotation.internalConfigurationAnnotationProcessor
class:[org.springframework.context.annotation.ConfigurationClassPostProcessor]
2 name:org.springframework.context.event.internalEventListenerFactory
class:[org.springframework.context.event.DefaultEventListenerFactory]
3 name:org.springframework.context.event.internalEventListenerProcessor
class:[org.springframework.context.event.EventListenerMethodProcessor]
4 name:org.springframework.context.annotation.internalAutowiredAnnotationProcessor
class:[org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor]
5 name:org.springframework.context.annotation.internalCommonAnnotationProcessor
class:[org.springframework.context.annotation.CommonAnnotationBeanPostProcessor]
代码说明:
/**
* Register all relevant annotation post processors in the given registry.
* @param registry the registry to operate on
* @param source the configuration source element (already extracted)
* that this registration was triggered from. May be {@code null}.
* @return a Set of BeanDefinitionHolders, containing all bean definitions
* that have actually been registered by this call
*/
public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
BeanDefinitionRegistry registry, @Nullable