In the " several custom initialization and destruction methods Spring lifecycle ," the last paragraph describes the start Spring container during initialization and destruction methods of execution timing, then Spring is how to do it?
Registration main configuration class
Spring uses AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Main.class);
the specified master configuration class, and to register it BeanFactory. In addition to the main configuration class, some basic post-processor will be registered to the BeanFactory class, as follows:
Initialization AnnotatedBeanDefinitionReader, internal processor register to post BeanFactory
- internalConfigurationAnnotationProcessor->ConfigurationClassPostProcessor
- internalAutowiredAnnotationProcessor->AutowiredAnnotationBeanPostProcessor
- internalCommonAnnotationProcessor->CommonAnnotationBeanPostProcessor
- internalPersistenceAnnotationProcessor->PersistenceAnnotationBeanPostProcessor
- internalEventListenerProcessor->EventListenerMethodProcessor
- internalEventListenerFactory->DefaultEventListenerFactory
Initialization ClassPathBeanDefinitionScanner, environmental load and resource allocation
- Environment
- ResourceLoader
refresh()
Spring core source very AbstractApplicationContext.refresh (), the name suggests, this is a method used to update the application context Spring, Spring container to initialize update operations.
// 部分源码
public void refresh() {
// 取出注册的 BeanFactory
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// 配置 BeanFactory
prepareBeanFactory(beanFactory);
// 初始化执行 BeanFactory 后置处理器
invokeBeanFactoryPostProcessors(beanFactory);
// 注册 Bean 后置处理器
registerBeanPostProcessors(beanFactory);
// 执行 Bean 后置处理器
finishBeanFactoryInitialization(beanFactory);
}
1, post-processor initialization execution BeanFactory
Overall order
First class will be executed in order to achieve BeanDefinitionRegistryPostProcessor
- BeanDefinitionRegistryPostProcessor PriorityOrdered of execution achieved.
- Execution of BeanDefinitionRegistryPostProcessor Ordered achieved.
- The implementation of all remaining BeanDefinitionRegistryPostProcessor.
Every step of the above will be the first in a container == initialization Bean ==, then go to the execution postProcessBeanDefinitionRegistry BeanDefinitionRegistryPostProcessor () method. Because BeanDefinitionRegistryPostProcessor inherited BeanFactoryPostProcessor, it will also perform postProcessBeanFactory () method.
Then executed in order to achieve class BeanFactoryPostProcessor
- BeanFactoryPostProcessor PriorityOrdered of execution achieved.
- Execution of BeanFactoryPostProcessor Ordered achieved.
- The implementation of all remaining BeanFactoryPostProcessor.
Every step of the above will be the first in a container == initialization Bean ==, then go to the execution postProcessBeanFactory BeanFactoryPostProcessor () method.
Implementation details
In ConfigurationClassPostProcessor an example, this class is BeanDefinitionRegistryPostProcessor implementation class, a class @Configuration annotation boot configuration class, the configuration of the main class at registration have registered the BeanFactory, in addition, also achieve such PriorityOrdered, seen from the execution sequence, it takes precedence.
1、ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry()
- First, find the main configuration categories, namely marked @Configuration class.
- A parser arranged to create class ConfigurationClassParser, an inlet to the main configuration class, which method doProcessConfigurationClass () will be marked according to type comments on the main configuration, in the following order of Spring find all components.
- @PropertySource configuration data loaded into the cache
- All the classes in the class @ComponentScan scan path, filtered annotation class @Component
- @Import loaded class @Import introduced. If the class is ImportSelector, will be to carry out its methods selectImports (); if it is ImportBeanDefinitionRegistrar, then just add the cache, it will not perform his method; otherwise, as a direct @Configuration annotation handling.
- @ImportResource
- Methods @Bean marked @Bean loaded.
- Interface default method
- father
- ConfigurationClassBeanDefinitionReader through all the components found and registered @Import imported class to BeanFactory. At this point, it performs ImportBeanDefinitionRegistrar.registerBeanDefinitions () method
2、ConfigurationClassPostProcessor.postProcessBeanFactory()
- Performing postProcessBeanFactory BeanDefinitionRegistryPostProcessor implementation class (), using the enhanced configuration class CGLib
- Sign up post-processors ImportAwareBeanPostProcessor
3、ImportAwareBeanPostProcessor.postProcessBeanFactory()
- Kai调 ImportAware.setImportMetadata ()
Follow the remaining postProcessBeanFactory BeanFactoryPostProcessor implementation class ()
So far, BeanFactoryPostProcessor and BeanDefinitionRegistryPostProcessor have been executed over, but part of the custom of Bean initialization has not started, you need to perform Bean post-processors.
2, post-processor performs Bean
This method will all single embodiment, the non-lazy loading objects instantiated.
The main processes:
- Initialization Bean == ==
- 回调SmartInitializingSingleton.afterSingletonsInstantiated()
At this point, the container Bean have been created, and then look at it is labeled == Yellow Bean == initialization process, " initialize and destroy several ways to customize the life cycle of Spring some of the processes" are described in the execution inside.
3, initialization Bean == ==
AbstractBeanFactory BeanFactory is the abstract implementation class, create Bean entrance is doGetBean (). First, it checks for the Bean cache, if there is direct access to, and return; if the cache is not present, look to create Bean processes.
AbstractAutowireCapableBeanFactory implements a method createBean AbstractBeanFactory create the Bean (), Spring will call its methods doCreateBean () to create a Bean instance.
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args) throws BeanCreationException {
// 1.反射执行构造器方法
BeanWrapper instanceWrapper = createBeanInstance(beanName, mbd, args);
// 属性赋值
populateBean(beanName, mbd, instanceWrapper);
// 初始化 Bean
exposedObject = initializeBean(beanName, exposedObject, mbd);->4.afterPropertiesSet->5.invokeCustomInitMethod
return exposedObject;
}
In the above-described source initializeBean () method will be executed sequentially
- BeanPostProcessor.postProcessBeforeInitialization()
- @PostConstruct
- InitializingBean.afterPropertiesSet()
- initMethod()
- BeanPostProcessor.postProcessAfterInitialization()
The main source code and comments as follows
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
// 执行 Aware 接口实现方法
invokeAwareMethods(beanName, bean);
// 2.执行 BeanPostProcessor.postProcessBeforeInitialization()
// 3.上面的方法内部实际上回去执行 @PostConstruct 注解的方法
applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
// 4.执行 InitializingBean.afterPropertiesSet()
// 5.然后执行自定义的 initMethod() 方法
invokeInitMethods(beanName, wrappedBean, mbd);
// 6.执行 BeanPostProcessor.postProcessAfterInitialization()
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
return wrappedBean;
}
Note that, initializeBean () method invokeAwareMethods () will go to perform the method of implementation of that interface section Aware, see the Spring Aware source .
to sum up
- When Spring starts, the first class and the configuration will be the primary basis for the post-processor to the class registration BeanFactory
- Call refresh () method, in the above-described post-processor BeanFactory removed, and performs post-processor implementation, the scan register to all available Bean BeanFactory
- The BeanFactory all available Bean final initialization