IOC容器的初始化过程,我这边分为两大步
1.容器的初始化
AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(MyConfig.class);
2.Bean的创建
Food food = annotationConfigApplicationContext.getBean("food", Food.class);
AnnotationConfigApplicationContext继承GenericApplicationContext,所以在初始化AnnotationConfigApplicationContext的时候,会先调用父类GenericApplicationContext的构造函数,而 DefaultListableBeanFactory实现了BeanDefinitionRegistry,所以最终AnnotationConfigApplicationContext既是一个BeanFactory,也是一个BeanDefinitionRegistry
- public GenericApplicationContext() {
- this.beanFactory = new DefaultListableBeanFactory();
- }
this.reader = new AnnotatedBeanDefinitionReader(this);
该方法最主要的作用就是注册内置的五个BeanDefinition到BeanDefinitionMap中,重点关注前两个
ConfigurationClassPostProcessor[实现BeanDefinitionRegistryPostProcessor]AutowiredAnnotationBeanPostProcessor[实现BeanPostProcessor]CommonAnnotationBeanPostProcessor[实现BeanPostProcessor]EventListenerMethodProcessor[实现BeanFactoryPostProcessor]DefaultEventListenerFactory
- public static Set
registerAnnotationConfigProcessors( - BeanDefinitionRegistry registry, @Nullable Object source) {
-
- DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
- if (beanFactory != null) {
- if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
- beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
- }
- if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
- beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
- }
- }
-
- Set
beanDefs = new LinkedHashSet<>(8); -
- if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
- RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
- def.setSource(source);
- beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
- }
-
- 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));
- }
-
- // Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor.
- if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {
- RootBeanDefinition def = new RootBeanDefinition();
- try {
- def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME,
- AnnotationConfigUtils.class.getClassLoader()));
- }
- catch (ClassNotFoundException ex) {
- throw new IllegalStateException(
- "Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex);
- }
- def.setSource(source);
- beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME));
- }
-
- if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) {
- RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class);
- def.setSource(source);
- beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME));
- }
-
- if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) {
- RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);
- def.setSource(source);
- beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));
- }
-
- return beanDefs;
- }
该scanner只有显式调用才会用到,不重要
annotationConfigApplicationContext.scan("com.lyf.study");
- public void register(Class>... componentClasses) {
- for (Class> componentClass : componentClasses) {
- registerBean(componentClass);
- }
- }
最终会到AnnotatedBeanDefinitionReader中的doRegisterBean方法中
关键步骤如下:
- if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
- return;
- }
BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
若手动注册为BeanDefinitionRegistryPostProcessor,则先执行其postProcessBeanDefinitionRegistry方法
注:BeanFactoryPostProcessor是BeanDefinitionRegistryPostProcessor的父类
BeanFactoryPostProcessor
有postProcessBeanFactory方法,主要用于修改BeanDefinitionMap中的BeanDefinition
BeanDefinitionRegistryPostProcessor
有postProcessBeanDefinitionRegistry方法,主要用于添加BeanDefinition到BeanDefinitionMap中
- //beanFactoryPostProcessors中的所有postProcessor都是显式调用annotationConfigApplicationContext.addBeanFactoryPostProcessor(null);来的
- for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
- if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
- BeanDefinitionRegistryPostProcessor registryProcessor =
- (BeanDefinitionRegistryPostProcessor) postProcessor;
- registryProcessor.postProcessBeanDefinitionRegistry(registry);
- registryProcessors.add(registryProcessor);
- }
- else {
- regularPostProcessors.add(postProcessor);
- }
- }
- String[] postProcessorNames =
- beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
- for (String ppName : postProcessorNames) {
- if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
- currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
- processedBeans.add(ppName);
- }
- }
- sortPostProcessors(currentRegistryProcessors, beanFactory);
- registryProcessors.addAll(currentRegistryProcessors);
- invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
- currentRegistryProcessors.clear();
这里默认情况下只会获取到reader中注册的5个内置的BeanFactoryPostProcessor中的ConfigurationClassPostProcessor,然后执行ConfigurationClassPostProcessor的postProcessBeanDefinitionRegistry方法
ConfigurationClassPostProcessor的postProcessBeanDefinitionRegistry非常的关键,它主要做了一下几件事:
(1)从beanFactory中获取所有已经注册到BeanDefinitionMap中的BeanDefinitionNames
(2)给使用了@Configuration注解的BeanDefinition打上full的标识[后续会使用cglib增强],给使用了@Order注解的BeanDefinition打上优先等级
(3)将符合(2)的所有BeanDefinition放入configCandidates列表中
(4)对configCandidates列表中的BeanDefinition,依据order属性值排序,值越小,优先级越高
(5)构建ConfigurationClassParser,解析每一个使用@Configuration的类,内部会对@Component、@PropertySource、@ComponentScan、@Import、@ImportResource、@Bean注解做处理
(6)将解析出来的对象转成BeanDefintion注册到BeanDefinitionMap中
- postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
- for (String ppName : postProcessorNames) {
- if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
- currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
- processedBeans.add(ppName);
- }
- }
- sortPostProcessors(currentRegistryProcessors, beanFactory);
- registryProcessors.addAll(currentRegistryProcessors);
- invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
- currentRegistryProcessors.clear();
- // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
- boolean reiterate = true;
- while (reiterate) {
- reiterate = false;
- postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
- for (String ppName : postProcessorNames) {
- if (!processedBeans.contains(ppName)) {
- currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
- processedBeans.add(ppName);
- reiterate = true;
- }
- }
- sortPostProcessors(currentRegistryProcessors, beanFactory);
- registryProcessors.addAll(currentRegistryProcessors);
- invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
- currentRegistryProcessors.clear();
- }
- // Now, invoke the postProcessBeanFactory callback of all processors handled so far.
- invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
- invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
- String[] postProcessorNames =
- beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
-
- // Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
- // Ordered, and the rest.
- List
priorityOrderedPostProcessors = new ArrayList<>(); - List
orderedPostProcessorNames = new ArrayList<>(); - List
nonOrderedPostProcessorNames = new ArrayList<>(); - for (String ppName : postProcessorNames) {
- if (processedBeans.contains(ppName)) {
- // skip - already processed in first phase above
- }
- else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
- priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
- }
- else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
- orderedPostProcessorNames.add(ppName);
- }
- else {
- nonOrderedPostProcessorNames.add(ppName);
- }
- }
-
- // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
- sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
- invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
-
- // Next, invoke the BeanFactoryPostProcessors that implement Ordered.
- List
orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size()); - for (String postProcessorName : orderedPostProcessorNames) {
- orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
- }
- sortPostProcessors(orderedPostProcessors, beanFactory);
- invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
-
- // Finally, invoke all other BeanFactoryPostProcessors.
- List
nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size()); - for (String postProcessorName : nonOrderedPostProcessorNames) {
- nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
- }
- invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
-
- // Clear cached merged bean definitions since the post-processors might have
- // modified the original metadata, e.g. replacing placeholders in values...
- beanFactory.clearMetadataCache();
依据内置的AutowiredAnnotationBeanPostProcessor和CommonAnnotationBeanPostProcessor对应的BeanDefinition,生成相对应的Bean,并添加到容器中
- BeanDefinitionRegistryPostProcessor
最先执行,主要用于添加BeanDefinition
- BeanFactoryPostProcessor
次要执行,主要用于修改BeanDefinition
- BeanPostProcessor
最后执行,在Bean初始化前会调用postProcessBeforeInitialization,在Bean初始化之后会 调用postProcessAfterInitialization
至此,容器大致的初始化过程结束.