目录
前言
整体流程图
容器初始化
容器创建和刷新
总结
前言
spring是一个高可用,易扩展的框架,为企业级应用的开发提供了一系列高可用的组件,包括且不仅包括如:spring核心技术(依赖注入、事件监听、aop等)、Testing测试、数据存取、spring mvc、与JMS、schedule等集成、对语言支持等。
本文主要介绍spring bean的生命周期。正文之前,先对spring相关的接口进行介绍。
实例化( instantiation )和初始化( initialization )
实例化是加载class文件,并在内存中开辟一块内容空间,创建一个属性值为默认值的对象。
初始化是对对象的属性进行赋值即属性填充。
容器接口 。 BeanFactory 是 spring 提供的进行容器管理的顶级接口,定义了 getBean 、 isSinglegton 、 getType 等获取 bean 、查看 bean 是单例还是原型类型的接口。其主要实现类包括:
HierarchicalBeanFactory :分层的 Bean 工厂,提供对父容器访问的功能。
ListableBeanFactory :可将 Bean 逐一列出的工厂。提供了一些列获取 bean 的方法,可进行 bean 枚举。
AutowireCapableBeanFactory :自动装配的 Bean 工厂 , 提供了自动装配的功能。
等......
通过不同的接口定义不同的顶级方法,体现了接口的单一职责、并通过子接口进行选择性继承父接口扩展不同的功能。
扩展接口。
容器扩展接口,如BeanFactoryPostProcessor接口提供容器初始化后,bean创建和初始化之前进行容器的功能增强。其还有一个功能强大的继承接口BeanDefinitionRegistryPostProcessor,该接口的方法会在BeanFactoryPostProcessor#postProcessBeanFactory方法调用之前进行,如ConfigurationClassPostProcessor就实现了BeanDefinitionRegistryPostProcessor接口,该processor主要功能就是进行扫描和BeanDefinition的注入,即对@Configuration,@ComponentScan等注解的解析工作。详细内容见正文。
Bean初始化前后扩展的接口, 如BeanPostProcessor接口能对bean的初始化前后进行扩展。该接口也有很多继承的子接口,如MergedBeanDefinitionPostProcessor、InstantiationAwareBeanPostProcessor接口,具体介绍见正文。
整体流程图
容器初始化
1. AnnotationConfigApplicationContext容器初始化的时候,会初始化AnnotatedBeanDefinitionReader。该reader进行初始化的时候会调用AnnotationConfigUtils#registerAnnotationConfigProcessors方法。
public static Set<BeanDefinitionHolder> 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<BeanDefinitionHolder> 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;
}
该方法会默认向容器注入
ConfigurationClassPostProcessor
AutowiredAnnotationBeanPostProcessor
CommonAnnotationBeanPostProcessor等processor的BeanDefinition对象,
ConfigurationClassPostProcessor主要是对@Configuration等注解进行解析,AutowiredAnnotationBeanPostProcessor主要是对注解了@Value、@Autowired的属性和方法进行创建bean之前的注入点注入,和填充属性时进行属性填充。CommonAnnotationBeanPostProcessor是对@Resource注解的处理
容器创建和刷新
容器的创建和刷新主要在AbstractApplicationContext#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();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
1.prepareRefresh()方法:主要时对容器前的刷新做准备工作,如设置上线文状态、初始等。
2.ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();方法主要是刷新容器销毁就的容器,创建新的容器(xml)。并加载配置文件中的beanDefinition对象。
下面这个容器刷新的方法是AbstractRefreshableApplicationContext子类的刷新方法
protected final void refreshBeanFactory() throws BeansException {
if (hasBeanFactory()) {
destroyBeans();
closeBeanFactory();
}
try {
DefaultListableBeanFactory beanFactory = createBeanFactory();
beanFactory.setSerializationId(getId());
customizeBeanFactory(beanFactory);
loadBeanDefinitions(beanFactory);
synchronized (this.beanFactoryMonitor) {
this.beanFactory = beanFactory;
}
}
catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
}
}
下面为GenericApplicationContext子类容器的刷新方法,具体子类具体分析
3.prepareBeanFactory(beanFactory);容器的准备工作,如注入ApplicationContextAwareProcessor,
并将系统环境信息和jvm信息注入到容器中。ApplicationContextAwareProcessor类就是为了在bean初始化之前调用实现了ApplicationContextAware的setApplicationContext方法,将容器对象暴露给实现接口,以便获取容器的相关信息。其他的Aware接口也类似。它实现了BeanPostProcessor接口,它的postProcessBeforeInitialization方法会在bean的初始化前调用。
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// Tell the internal bean factory to use the context's class loader etc.
beanFactory.setBeanClassLoader(getClassLoader());
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// Configure the bean factory with context callbacks.
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
// BeanFactory interface not registered as resolvable type in a plain factory.
// MessageSource registered (and found for autowiring) as a bean.
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);
// Register early post-processor for detecting inner beans as ApplicationListeners.
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
// Detect a LoadTimeWeaver and prepare for weaving, if found.
if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
// Set a temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
// Register default environment beans.
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);从该方法开始就开始进入了bean的生命周期,该方法主要是对容器创建的增强,如spring提供的ConfigurationClassPostProcessor类,完成对spring容器的扫描并将注解了@Configuration、@ComponentScan、@Import等注解的类加入BeanDefinition的map中,完成beanDefinition对象的封装和注册。他的调用顺序是先调用实现了BeanDefinitionRegistryPostProcessor接口的postProcessBeanDefinitionRegistry方法,然后在调用实现了BeanFactoryPostProcessor接口的postProcessBeanFactory方法。由于ConfigurationClassPostProcessor类的beandefinition信息在容器准备的时候进行了注册,上文已经提过。beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)该方法,如果容器中没有找到,就会进行ConfigurationClassPostProcessor类对象的创建。invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);完成该方法调用。
Spring在调用BeanDefinitionRegistryPostProcessor时,会调用三次,其调用先后顺序是这样的:
1.如果类实现了BeanDefinitionRegistryPostProcessor,并且实现了PriorityOrdered
2.如果类实现了BeanDefinitionRegistryPostProcessor,并且实现了Ordered
3.如果类只实现了BeanDefinitionRegistryPostProcessor
源码如下:
public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
// Invoke BeanDefinitionRegistryPostProcessors first, if any.
Set<String> processedBeans = new HashSet<>();
if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
BeanDefinitionRegistryPostProcessor registryProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
registryProcessor.postProcessBeanDefinitionRegistry(registry);
registryProcessors.add(registryProcessor);
}
else {
regularPostProcessors.add(postProcessor);
}
}
// 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.
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);
currentRegistryProcessors.clear();
// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
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);
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);
currentRegistryProcessors.clear();
}
// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
}
else {
// Invoke factory processors registered with the context instance.
invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
}
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
List<String> 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<BeanFactoryPostProcessor> 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<BeanFactoryPostProcessor> 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();
}
6.registerBeanPostProcessors(beanFactory);根据beandefinition对象完成部分BeanPostProcessor对象的注册,如上文提过的AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);registerBeanPostProcessors(beanFactory, orderedPostProcessors);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();方法。初始化国际化工具类MessageSource
8.initApplicationEventMulticaster();初始化事件广播器
9.onRefresh();模板方法,在容器刷新的时候可以自定义逻辑(子类自己去实现逻辑),不同的Spring容器做不同的事情。如内嵌的tomcat容器的创建就在此方法进行。
10.registerListeners();注册监听器,并且广播early application events,也就是早期的事件
11.finishBeanFactoryInitialization(beanFactory);初始化、实例化所有非懒加载的单例bean,此过程中各个BeanPostProcessor都会起作用。如
- 实例化前会调用实现了InstantiationAwareBeanPostProcessor接口的postProcessBeforeInstantiation方法,如AbstractAutoProxyCreator#postProcessBeforeInstantiation方法提前创建aop代理对象。
- createBeanInstance方法创建BeanWrapper对象,如果没有构造方法则使用默认构造方法进行反射创建对象,如果有多个构造方法,先查询多个候选的构造方法,选取有效的构造方法进行反射创建对象,例如有多个构造方法时,会采用注解了@Autowired的构造方法进行反射初始化。
- 实例化后调用applyMergedBeanDefinitionPostProcessors方法,实例化后会调用实现了MergedBeanDefinitionPostProcessor接口的postProcessMergedBeanDefinition方法,如
- AutowiredAnnotationBeanPostProcessor#postProcessMergedBeanDefinition方法会将注解了@Autowiredg和@Value注解的方法或者属性以InjectionMetadata对象注入到injectionMetadataCache map中。
- CommonAnnotationBeanPostProcessor#postProcessMergedBeanDefinition方法会将注解了@Resource注解的方法或者属性以InjectionMetadata对象注入到injectionMetadataCache的map中
- InitDestroyAnnotationBeanPostProcessor#postProcessMergedBeanDefinition方法会将注解了@PostConstructor等生命周期注解的方法以LifecycleMetadata对象注入lifecycleMetadataCache的map到。
- 属性填充populateBean,会先调用 InstantiationAwareBeanPostProcessor的postProcessAfterInstantiation,然后调用实现了InstantiationAwareBeanPostProcessor接口的postProcessPropertyValues方法。
- AutowiredAnnotationBeanPostProcessor#postProcessPropertyValues方法会拿到对应的InjectionMetadata对象将注解了@Autowired和@Value的方法或者属性进行反射赋值。
- CommonAnnotationBeanPostProcessor#postProcessPropertyValues与上面类似
- 初始化前调用invokeAwareMethods
- 1、BeanNameAware的setBeanName方法。
- 2. BeanClassLoaderAware接口的setBeanClassLoader方法。
- 3. BeanFactoryAware接口的setBeanFactory方法
- 初始化前调用applyBeanPostProcessorsBeforeInitialization方法,applyBeanPostProcessorsBeforeInitialization方法会调用实现了BeanPostProcessor接口的postProcessBeforeInitialization方法如
- 1.ApplicationContextAwareProcessor#postProcessBeforeInitialization方法处理实现了ApplicationContextAware的setApplicationContext方法等一系列Aware。
- 2.InitDestroyAnnotationBeanPostProcessor#postProcessBeforeInitialization方法拿到初始化前注入的生命周期方法进行反射调用。及@PostConstuctor等生命周期注解的方法。
- 初始化 invokeInitMethods,invokeInitMethods方法调用实现了InitializingBean的afterPropertiesSet进行属性赋值,然后再调用init-method方法
- 初始化后applyBeanPostProcessorsAfterInitialization方法,applyBeanPostProcessorsAfterInitialization方法调用实现了BeanPostProcessor接口的postProcessAfterInitialization方法。如AbstractAutoProxyCreator#postProcessAfterInitialization方法进行aop的代理创建工作。
12.finishRefresh();初始化上下文的生命周期处理器,并刷新(找出Spring容器中实现了Lifecycle接口的bean并执行start()方法),发布ContextRefreshedEvent事件告知对应的ApplicationListener进行响应的操作
总结
1.如何对spring进行扩展,像aop和mybatis一样,通过spring提供的增强器进行功能的扩展。
2.感受spring整体架构的设计之美,通过接口隔离,接口多实现、单例模式、工厂模式、动态代理、模板方法模式、策略模式等设计原则和设计模式,进行整体架构的设计,最终达到高可用,易扩展等优点。
3.通过各种缓存设计,解决不同的应用场景。如循环依赖的三级缓存等。