赞
踩
Spring的IOC启动的过程重点在于其refresh(); 方法。
其源码关键节点转化为流程图如下:
prepareRefresh(); // Prepare this context for refreshing. 刷新前的预处理;
// Prepare this context for refreshing.
prepareRefresh();
protected void prepareRefresh() { // Switch to active. // 初始化值 this.startupDate = System.currentTimeMillis(); this.closed.set(false); this.active.set(true); if (logger.isDebugEnabled()) { if (logger.isTraceEnabled()) { logger.trace("Refreshing " + this); } else { logger.debug("Refreshing " + getDisplayName()); } } // Initialize any placeholder property sources in the context environment. // 子类自定义个性化属性方法 initPropertySources(); // Validate that all properties marked as required are resolvable: // see ConfigurablePropertyResolver#setRequiredProperties // 校验环境属性合法性 getEnvironment().validateRequiredProperties(); // 保存一些早期事件监听器 // Store pre-refresh ApplicationListeners... if (this.earlyApplicationListeners == null) { this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners); } else { // Reset local application listeners to pre-refresh state. this.applicationListeners.clear(); this.applicationListeners.addAll(this.earlyApplicationListeners); } // Allow for the collection of early ApplicationEvents, // to be published once the multicaster is available... this.earlyApplicationEvents = new LinkedHashSet<>(); }
该步骤较为重点的操作为:
1)initPropertySources(); 初始化一些属性设置;子类自定义个性化的属性设置方法
2)getEnvironment().validateRequiredProperties(); 校验环境属性合法性
3)保存一些早期事件监听器至 this.applicationListeners
obtainFreshBeanFactory(); 初始化BeanFactory
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
refreshBeanFactory();
return getBeanFactory();
}
该步骤较为重点的操作为:
1)refreshBeanFactory(); 刷新BeanFactory;
protected final void refreshBeanFactory() throws BeansException { // 存在BeanFactory则先销毁关闭 if (hasBeanFactory()) { destroyBeans(); closeBeanFactory(); } try { // 初始化BeanFactory this.beanFactory = new DefaultListableBeanFactory(); DefaultListableBeanFactory beanFactory = createBeanFactory(); // 赋值ID beanFactory.setSerializationId(getId()); customizeBeanFactory(beanFactory); // beanFactory——加载Bean定义信息 loadBeanDefinitions(beanFactory); this.beanFactory = beanFactory; } catch (IOException ex) { throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex); } }
2)getBeanFactory(); 返回刚才创建的beanFactory对象
prepareBeanFactory(beanFactory); BeanFactory的预准备工作(对初始化的BeanFactory进行一些设置);
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
该步骤较为重点的操作为:
1)设置BeanFactory的类加载器、支持表达式解析器…
beanFactory.setBeanClassLoader(getClassLoader());
if (!shouldIgnoreSpel) {
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
}
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
2)添加部分的后置处理器【ApplicationContextAwareProcessor】
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
3)设置忽略自动装配的接口,对于实现这些接口的类容器不进行自动注入;
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.ignoreDependencyInterface(ApplicationStartupAware.class);
4)设置可以解析的自动装配;我们可以直接在任何组件中自动注入(@AutoWire)
BeanFactory、ResourceLoader、ApplicationEventPublisher、ApplicationContext
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);
5)添加后置处理器【ApplicationListenerDetector】用于 ApplicationListeners 事件监听器;
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
6)给BeanFactory中注册一些能用的组件;environment【ConfigurableEnvironment】、systemProperties、systemEnvironment、applicationStartup
// 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());
}
if (!beanFactory.containsLocalBean(APPLICATION_STARTUP_BEAN_NAME)) {
beanFactory.registerSingleton(APPLICATION_STARTUP_BEAN_NAME, getApplicationStartup());
}
postProcessBeanFactory(beanFactory); BeanFactory准备工作完成后进行的后置处理器工作;
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
}
子类通过重写这个方法来在BeanFactory创建并预准备完成以后做进一步的设置。
例如子类:ServletWebServerApplicationContext 的 postProcessBeanFactory()
添加了一个后置处理器、忽略了ServletContextAware、注册了web的作用域信息。
invokeBeanFactoryPostProcessors(beanFactory); 执行BeanFactoryPostProcessors;
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
// 执行部分类型后置处理器
PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
......
}
该步骤较为重点的操作为:
执行了两个特殊的后置处理器:BeanDefinitionRegistryPostProcessor 和 BeanFactoryPostProcessors
先执行 BeanDefinitionRegistryPostProcessor
1)获取所有的BeanDefinitionRegistryPostProcessor;
2)先执行实现了PriorityOrdered优先级接口的BeanDefinitionRegistryPostProcessor、
3)在执行实现了Ordered顺序接口的BeanDefinitionRegistryPostProcessor;
4)最后执行没有实现任何优先级或者是顺序接口的BeanDefinitionRegistryPostProcessors;
invokeBeanDefinitionRegistryPostProcessors() -> postProcessBeanDefinitionRegistry()
invokeBeanFactoryPostProcessors() -> postProcessBeanFactory()
再执行BeanFactoryPostProcessor的方法
1)获取所有的BeanFactoryPostProcessor
2)看先执行实现了PriorityOrdered优先级接口的BeanFactoryPostProcessor;
3)在执行实现了Ordered顺序接口的BeanFactoryPostProcessor;
4)最后执行没有实现任何优先级或者是顺序接口的BeanFactoryPostProcessor;
invokeBeanFactoryPostProcessors() -> postProcessBeanFactory()
registerBeanPostProcessors(beanFactory); 注册bean的后置处理器;
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}
不同接口类型的 BeanPostProcessor,在bean创建前后执行的时机是不一样的
BeanPostProcessor 接口还存在多个子接口:
DestructionAwareBeanPostProcessor、
InstantiationAwareBeanPostProcessor、
SmartInstantiationAwareBeanPostProcessor、
MergedBeanDefinitionPostProcessor【internalPostProcessors】…等等
该步骤较为重点的操作为:
1)所有的后置处理器 BeanPostProcessor,都可以默认通过PriorityOrdered、Ordered接口来执行优先级
2)先注册 PriorityOrdered 优先级接口的BeanPostProcessor
把每个BeanPostProcessor添加至 BeanFactory中
registerBeanPostProcessors(beanFactory, orderedPostProcessors); -> beanFactory.addBeanPostProcessor(postProcessor);
private static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanPostProcessor> postProcessors) {
if (beanFactory instanceof AbstractBeanFactory) {
// Bulk addition is more efficient against our CopyOnWriteArrayList there
((AbstractBeanFactory) beanFactory).addBeanPostProcessors(postProcessors);
}
else {
for (BeanPostProcessor postProcessor : postProcessors) {
beanFactory.addBeanPostProcessor(postProcessor);
}
}
}
3)再注册实现Ordered接口的BeanPostProcessor
4)再注册没有实现任何优先级接口的
5)最后注册 MergedBeanDefinitionPostProcessor
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
// Finally, re-register all internal BeanPostProcessors.
sortPostProcessors(internalPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, internalPostProcessors);
6)添加一个 ApplicationListenerDetector :在bean创建完成后检查bean是否是 ApplicationListener
如果是则添加至 this.applicationContext.addApplicationListener((ApplicationListener<?>) bean);
// 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));
initMessageSource(); 初始化MessageSource组件(做国际化功能、消息绑定、消息解析);
// Initialize message source for this context.
initMessageSource();
protected void initMessageSource() { ConfigurableListableBeanFactory beanFactory = getBeanFactory(); // 查看容器中是否存在 id为messageSource的,类型是MessageSource的组件 if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) { // 有则赋值给 messageSource this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class); // Make MessageSource aware of parent MessageSource. // 设置 messageSource的父级 if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) { HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource; if (hms.getParentMessageSource() == null) { // Only set parent context as parent MessageSource if no parent MessageSource // registered already. hms.setParentMessageSource(getInternalParentMessageSource()); } } if (logger.isTraceEnabled()) { logger.trace("Using MessageSource [" + this.messageSource + "]"); } } else { // 没有自己创建一个DelegatingMessageSource; // Use empty MessageSource to be able to accept getMessage calls. DelegatingMessageSource dms = new DelegatingMessageSource(); dms.setParentMessageSource(getInternalParentMessageSource()); // 把创建好的MessageSource注册在容器中,以后获取国际化配置文件的值的时候,可以自动注入MessageSource; this.messageSource = dms; beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource); if (logger.isTraceEnabled()) { logger.trace("No '" + MESSAGE_SOURCE_BEAN_NAME + "' bean, using [" + this.messageSource + "]"); } } }
MessageSource:取出国际化配置文件中的某个key的值;能按照区域信息获取;
该步骤较为重点的操作为:
1)看容器中是否有id为messageSource的,类型是MessageSource的组件.
if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) ?
2)容器中存在,取到bean赋值给messageSource
3)容器中不存在,自己创建一个DelegatingMessageSource;
把创建好的MessageSource注册在容器中,以后获取国际化配置文件的值的时候,可以自动注入MessageSource;
beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
initApplicationEventMulticaster(); 初始化事件派发器;事件派发器用于事件监听和派发。
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
protected void initApplicationEventMulticaster() { ConfigurableListableBeanFactory beanFactory = getBeanFactory(); // 查询是否存在ID为:applicationEventMulticaster 的bean if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) { // 存在给 this.applicationEventMulticaster 赋值 this.applicationEventMulticaster = beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class); if (logger.isTraceEnabled()) { logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]"); } } else { // 没有这初始化创建多播器 this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory); // 并加到容器中,自动注入这个 applicationEventMulticaster beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster); if (logger.isTraceEnabled()) { logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " + "[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]"); } } }
onRefresh(); 子类重写这个方法,在容器刷新的时候可以自定义逻辑;
// Initialize other special beans in specific context subclasses.
onRefresh();
protected void onRefresh() throws BeansException {
// For subclasses: do nothing by default.
}
registerListeners(); 注册事件监听器;
// Check for listener beans and register them.
registerListeners();
protected void registerListeners() { // Register statically specified listeners first. // 获取已有的 this.applicationListeners 所有监听器 ApplicationListener for (ApplicationListener<?> listener : getApplicationListeners()) { // 监听器加入到事件派发器中 getApplicationEventMulticaster().addApplicationListener(listener); } // Do not initialize FactoryBeans here: We need to leave all regular beans // uninitialized to let post-processors apply to them! // 获取ApplicationListener类的监听器 String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false); // 监听器加入到事件派发器中 for (String listenerBeanName : listenerBeanNames) { getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName); } // Publish early application events now that we finally have a multicaster... // 派发之前步骤产生的提前事件; this.earlyApplicationEvents Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents; this.earlyApplicationEvents = null; if (!CollectionUtils.isEmpty(earlyEventsToProcess)) { for (ApplicationEvent earlyEvent : earlyEventsToProcess) { getApplicationEventMulticaster().multicastEvent(earlyEvent); } } }
该步骤较为重点的操作为:
1)从容器中拿到所有的监听器 ApplicationListener.class
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
2)把他们注册到 applicationEventMulticaster (事件多播器)中
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
3)派发之前步骤产生的事件; this.earlyApplicationEvents
getApplicationEventMulticaster().multicastEvent(earlyEvent);
finishBeanFactoryInitialization(beanFactory); 初始化剩下的单实例bean;
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// ......
// Instantiate all remaining (non-lazy-init) singletons.
// 初始化后剩下的单实例bean
beanFactory.preInstantiateSingletons();
}
public void preInstantiateSingletons() throws BeansException { if (logger.isTraceEnabled()) { logger.trace("Pre-instantiating singletons in " + this); } // 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. // 1)获取容器中所有的bean List<String> beanNames = new ArrayList<>(this.beanDefinitionNames); // Trigger initialization of all non-lazy singleton beans... for (String beanName : beanNames) { // 2)获取bean的定义信息 RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName); // 3)bean不是抽象的,是单实例,不是懒加载的 if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) { // 判断是否是FactoryBean;是否是实现FactoryBean接口的Bean;是则为FactoryBean创建bean,使用其getObject()返回的bean if (isFactoryBean(beanName)) { Object bean = getBean(FACTORY_BEAN_PREFIX + beanName); if (bean instanceof FactoryBean) { FactoryBean<?> factory = (FactoryBean<?>) bean; boolean isEagerInit; if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) { isEagerInit = AccessController.doPrivileged( (PrivilegedAction<Boolean>) ((SmartFactoryBean<?>) factory)::isEagerInit, getAccessControlContext()); } else { isEagerInit = (factory instanceof SmartFactoryBean && ((SmartFactoryBean<?>) factory).isEagerInit()); } if (isEagerInit) { getBean(beanName); } } } else { // 4)利用getBean(beanName) -> doGetBean() ;创建对象 getBean(beanName); } } } // Trigger post-initialization callback for all applicable beans... // 5)所有的bean都利用getBean()创建完成后 for (String beanName : beanNames) { Object singletonInstance = getSingleton(beanName); // bean 是否为 SmartInitializingSingleton,为则执行其 afterSingletonsInstantiated()方法 if (singletonInstance instanceof SmartInitializingSingleton) { StartupStep smartInitialize = this.getApplicationStartup().start("spring.beans.smart-initialize") .tag("beanName", beanName); SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance; if (System.getSecurityManager() != null) { AccessController.doPrivileged((PrivilegedAction<Object>) () -> { smartSingleton.afterSingletonsInstantiated(); return null; }, getAccessControlContext()); } else { // SmartInitializingSingleton -> afterSingletonsInstantiated() smartSingleton.afterSingletonsInstantiated(); } smartInitialize.end(); } } }
重点解析一下第四点 —— 创建对象
protected <T> T doGetBean( String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly) throws BeansException { String beanName = transformedBeanName(name); Object beanInstance; // Eagerly check singleton cache for manually registered singletons. // 1)getSingleton(beanName); 先获取缓存中保存的单实例bean Object sharedInstance = getSingleton(beanName); // 获取的bean不为空,则获取bean实例返回 if (sharedInstance != null && args == null) { if (logger.isTraceEnabled()) { if (isSingletonCurrentlyInCreation(beanName)) { logger.trace("Returning eagerly cached instance of singleton bean '" + beanName + "' that is not fully initialized yet - a consequence of a circular reference"); } else { logger.trace("Returning cached instance of singleton bean '" + beanName + "'"); } } beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, null); } // 2)缓存中获取不到,开始bean的创建过程 else { // ...... if (!typeCheckOnly) { // 3)首先标记当前bean已经被创建,保证bean的单例; markBeanAsCreated(beanName); } StartupStep beanCreation = this.applicationStartup.start("spring.beans.instantiate") .tag("beanName", name); try { if (requiredType != null) { beanCreation.tag("beanType", requiredType::toString); } // 4)获取bean的定义信息;RootBeanDefinition RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); checkMergedBeanDefinition(mbd, beanName, args); // Guarantee initialization of beans that the current bean depends on. // 5)获取当前bean依赖的其他bean;如果有按照getBean()把依赖的bean先创建出来; String[] dependsOn = mbd.getDependsOn(); if (dependsOn != null) { for (String dep : dependsOn) { if (isDependent(beanName, dep)) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'"); } registerDependentBean(dep, beanName); try { getBean(dep); } catch (NoSuchBeanDefinitionException ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "'" + beanName + "' depends on missing bean '" + dep + "'", ex); } } } // Create bean instance. if (mbd.isSingleton()) { // 7)将创建的bean添加到缓存中 singletonObjects,ioc容器就是这些map;很多的map里面保存了单实例beans,环境信息.... // getSingleton() -> addSingleton(beanName, singletonObject); sharedInstance = getSingleton(beanName, () -> { try { // 6)启动单实例bean的创建流程 return createBean(beanName, mbd, args); } }); beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); } else if (mbd.isPrototype()) { // It's a prototype -> create a new instance. Object prototypeInstance = null; try { beforePrototypeCreation(beanName); prototypeInstance = createBean(beanName, mbd, args); } finally { afterPrototypeCreation(beanName); } beanInstance = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd); } else { String scopeName = mbd.getScope(); if (!StringUtils.hasLength(scopeName)) { throw new IllegalStateException("No scope name defined for bean ´" + beanName + "'"); } Scope scope = this.scopes.get(scopeName); if (scope == null) { throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'"); } try { Object scopedInstance = scope.get(beanName, () -> { beforePrototypeCreation(beanName); try { return createBean(beanName, mbd, args); } finally { afterPrototypeCreation(beanName); } }); beanInstance = getObjectForBeanInstance(scopedInstance, name, beanName, mbd); } catch (IllegalStateException ex) { throw new ScopeNotActiveException(beanName, scopeName, ex); } } } finally { beanCreation.end(); } } return adaptBeanInstance(name, beanInstance, requiredType); }
重点解析 第 6)启动单实例bean的创建流程
createBean(beanName, mbd, args); 创建bean
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)给BeanPostProcessors一个返回代理而不是目标bean实例的机会。 Object bean = resolveBeforeInstantiation(beanName, mbdToUse); // 2)如果步骤1,有代理对象,则直接返回 if (bean != null) { return bean; } } try { // 3)创建对象 Object beanInstance = doCreateBean(beanName, mbdToUse, args); if (logger.isTraceEnabled()) { logger.trace("Finished creating instance of bean '" + beanName + "'"); } return beanInstance; } // ...... }
1)Object bean = resolveBeforeInstantiation(beanName, mbdToUse); BeanPostProcessors返回代理对象
让BeanPostProcessor先拦截【InstantiationAwareBeanPostProcessor】,返回代理对象【AOP自动配置开启原理】
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) { Object bean = null; if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) { // Make sure bean class is actually resolved at this point. // 判断 BeanPostProcessor 是否存在 InstantiationAwareBeanPostProcessor if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { Class<?> targetType = determineTargetType(beanName, mbd); if (targetType != null) { // 先触发:postProcessBeforeInstantiation(); bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName); // 如果有返回值:触发postProcessAfterInitialization(); if (bean != null) { bean = applyBeanPostProcessorsAfterInitialization(bean, beanName); } } } mbd.beforeInstantiationResolved = (bean != null); } return bean; }
2)如果步骤1,有代理对象,则直接返回
3)如果步骤1没值,这进行bean的创建
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException { // Instantiate the bean. BeanWrapper instanceWrapper = null; if (mbd.isSingleton()) { instanceWrapper = this.factoryBeanInstanceCache.remove(beanName); } if (instanceWrapper == null) { // 1)【创建bean实例】利用工厂方法或者对象的构造器 instanceWrapper = createBeanInstance(beanName, mbd, args); } Object bean = instanceWrapper.getWrappedInstance(); Class<?> beanType = instanceWrapper.getWrappedClass(); if (beanType != NullBean.class) { mbd.resolvedTargetType = beanType; } // Allow post-processors to modify the merged bean definition. synchronized (mbd.postProcessingLock) { if (!mbd.postProcessed) { try { // 2)调用 MergedBeanDefinitionPostProcessor -> postProcessMergedBeanDefinition() applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); } mbd.postProcessed = true; } } // ...... // Initialize the bean instance. Object exposedObject = bean; try { // 3)【bean属性赋值】上述对bean进行实例化了,但是bean并没有具体的属性值 populateBean(beanName, mbd, instanceWrapper); // 4)【bean初始化】 exposedObject = initializeBean(beanName, exposedObject, mbd); } // ...... // Register bean as disposable. // 5)注册bean的销毁方法 DisposableBeanAdapter -> DisposableBean try { registerDisposableBeanIfNecessary(beanName, bean, mbd); } catch (BeanDefinitionValidationException ex) { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex); } return exposedObject; }
3)【bean属性赋值】上述对bean进行实例化了,但是bean并没有具体的属性值
populateBean(beanName, mbd, instanceWrapper);
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) { // ...... // 1)赋值之前 hasInstantiationAwareBeanPostProcessors() 判断是否为 InstantiationAwareBeanPostProcessor if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) { // 执行 InstantiationAwareBeanPostProcessor -> postProcessAfterInstantiation() if (!bp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) { return; } } } PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null); // ...... // 2)再次拿到 InstantiationAwareBeanPostProcessor 后置处理器 boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors(); boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE); PropertyDescriptor[] filteredPds = null; if (hasInstAwareBpps) { if (pvs == null) { pvs = mbd.getPropertyValues(); } // 调用 postProcessProperties() 、 postProcessPropertyValues() 方法 获取bean属性的值 for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) { PropertyValues pvsToUse = bp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName); if (pvsToUse == null) { if (filteredPds == null) { filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching); } pvsToUse = bp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName); if (pvsToUse == null) { return; } } pvs = pvsToUse; } } // ...... // 3)应用bean属性的值:为属性利用setter方法进行赋值 if (pvs != null) { applyPropertyValues(beanName, mbd, bw, pvs); } }
4)【bean初始化】
exposedObject = initializeBean(beanName, exposedObject, mbd);
protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) { // 1)【执行Aware接口方法】执行部分xxxAware接口的方法; invokeAwareMethods(beanName, bean); if (System.getSecurityManager() != null) { AccessController.doPrivileged((PrivilegedAction<Object>) () -> { invokeAwareMethods(beanName, bean); return null; }, getAccessControlContext()); } else { invokeAwareMethods(beanName, bean); } Object wrappedBean = bean; if (mbd == null || !mbd.isSynthetic()) { // 2)【执行后置处理器之前方法】 BeanPostProcessor -> postProcessBeforeInitialization(result, beanName); wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName); } try { // 3) 【执行初始化方法】 invokeInitMethods(beanName, wrappedBean, mbd); } if (mbd == null || !mbd.isSynthetic()) { // 4)【执行后置处理器之后方法】 BeanPostProcessor -> postProcessAfterInitialization(result, beanName); wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName); } return wrappedBean; }
3)【执行初始化方法】invokeInitMethods(beanName, wrappedBean, mbd);
1)bean是否是 InitializingBean 接口的实现;是执行接口规定的初始化方法
((InitializingBean) bean).afterPropertiesSet();
2)是否自定义初始化方法; getInitMethodName();
mbd.getInitMethodName(); ——》invokeCustomInitMethod(beanName, bean, mbd);
finishRefresh(); 完成BeanFactory的初始化创建工作;IOC容器创建完成;
// Last step: publish corresponding event.
finishRefresh();
protected void finishRefresh() { // Clear context-level resource caches (such as ASM metadata from scanning). // 清除上下文级别的资源缓存(如扫描中的ASM元数据) clearResourceCaches(); // Initialize lifecycle processor for this context. // 初始化和生命周期有关的后置处理器; LifecycleProcessor initLifecycleProcessor(); // Propagate refresh to lifecycle processor first. // 获取前面的生命周期处理器,回调其onRefresh()方法 getLifecycleProcessor().onRefresh(); // Publish the final event. // 发布容器刷新完成事件; publishEvent(new ContextRefreshedEvent(this)); // Participate in LiveBeansView MBean, if active. // 注册MBean if (!NativeDetector.inNativeImage()) { LiveBeansView.registerApplicationContext(this); } }
该步骤较为重点的操作为:
1)clearResourceCaches(); 清除上下文级别的资源缓存(如扫描中的ASM元数据)
2)initLifecycleProcessor(); 初始化和生命周期有关的后置处理器; LifecycleProcessor
默认从容器中找是否有lifecycleProcessor的组件【LifecycleProcessor】;如果没有new DefaultLifecycleProcessor(),加入到容器;
LifecycleProcessor -> void onRefresh(); / void onClose();
3)getLifecycleProcessor().onRefresh(); 获取前面的生命周期处理器,回调其onRefresh()方法
4)publishEvent(new ContextRefreshedEvent(this)); 发布容器刷新完成事件;
5)LiveBeansView.registerApplicationContext(this); 注册MBean
Spring容器的 refresh(); 【创建和刷新】: 1)prepareRefresh(); // Prepare this context for refreshing. 刷新前的预处理; 1)initPropertySources(); 初始化一些属性设置;子类自定义个性化的属性设置方法 2)getEnvironment().validateRequiredProperties(); 校验环境属性合法性 3)保存一些早期事件监听器至 this.applicationListeners 2)beanFactory = obtainFreshBeanFactory(); 获取BeanFactory; 1)refreshBeanFactory(); 刷新BeanFactory; 在 GenericApplicationContext 创建了 this.beanFactory = new DefaultListableBeanFactory(); 赋值了ID this.beanFactory.setSerializationId(getId()); 2)getBeanFactory(); 返回刚才创建的beanFactory对象 3)prepareBeanFactory(beanFactory); BeanFactory的预准备工作(对初始化的BeanFactory进行一些设置); 1)设置BeanFactory的类加载器、支持表达式解析器... 2)添加部分的后置处理器【ApplicationContextAwareProcessor】 beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this)); 3)设置忽略自动装配的接口,对于实现这些接口的类容器不进行自动注入; beanFactory.ignoreDependencyInterface(EnvironmentAware.class); beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);... 4)设置可以解析的自动装配;我们可以直接在任何组件中自动注入(@AutoWire) beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory); beanFactory.registerResolvableDependency(ApplicationContext.class, this);...ResourceLoader、ApplicationEventPublisher 5)添加后置处理器【ApplicationListenerDetector】用于 ApplicationListeners 事件监听器; 6)给BeanFactory中注册一些能用的组件;environment【ConfigurableEnvironment】、systemProperties、systemEnvironment、applicationStartup 4)postProcessBeanFactory(beanFactory); BeanFactory准备工作完成后进行的后置处理器工作; 子类通过重写这个方法来在BeanFactory创建并预准备完成以后做进一步的设置 ===================================== 以上为BeanFactory的预创建和准备工作 ============================================================== 5)invokeBeanFactoryPostProcessors(beanFactory); 执行BeanFactoryPostProcessors; BeanFactoryPostProcessors 和 BeanDefinitionRegistryPostProcessor 先执行 BeanDefinitionRegistryPostProcessor 1)、获取所有的BeanDefinitionRegistryPostProcessor; 2)、先执行实现了PriorityOrdered优先级接口的BeanDefinitionRegistryPostProcessor、 3)、在执行实现了Ordered顺序接口的BeanDefinitionRegistryPostProcessor; 4)、最后执行没有实现任何优先级或者是顺序接口的BeanDefinitionRegistryPostProcessors; invokeBeanDefinitionRegistryPostProcessors() -> postProcessBeanDefinitionRegistry() invokeBeanFactoryPostProcessors() -> postProcessBeanFactory() 再执行BeanFactoryPostProcessor的方法 BeanFactoryPostProcessors:BeanFactory的后置处理器,在BeanFactory标准初始化之后执行的; 执行 invokeBeanFactoryPostProcessors() 方法 1)、获取所有的BeanFactoryPostProcessor 2)、看先执行实现了PriorityOrdered优先级接口的BeanFactoryPostProcessor、 3)、在执行实现了Ordered顺序接口的BeanFactoryPostProcessor; 4)、最后执行没有实现任何优先级或者是顺序接口的BeanFactoryPostProcessor; invokeBeanFactoryPostProcessors() -> postProcessBeanFactory() 6)registerBeanPostProcessors(beanFactory); 注册bean的后置处理器; 不同接口类型的 BeanPostProcessor,在bean创建前后执行的时机是不一样的 BeanPostProcessor 接口还存在多个子接口: DestructionAwareBeanPostProcessor、 InstantiationAwareBeanPostProcessor、 SmartInstantiationAwareBeanPostProcessor、 MergedBeanDefinitionPostProcessor【internalPostProcessors】...等等 1)所有的后置处理器 BeanPostProcessor,都可以默认通过PriorityOrdered、Ordered接口来执行优先级 2)先注册 PriorityOrdered 优先级接口的BeanPostProcessor 把每个BeanPostProcessor添加至 BeanFactory中 registerBeanPostProcessors(beanFactory, orderedPostProcessors); -> beanFactory.addBeanPostProcessor(postProcessor); 3)再注册实现Ordered接口的BeanPostProcessor 4)再注册没有实现任何优先级接口的 5)最后注册 MergedBeanDefinitionPostProcessor 6)添加一个 ApplicationListenerDetector :在bean创建完成后检查bean是否是 ApplicationListener 如果是则添加至 this.applicationContext.addApplicationListener((ApplicationListener<?>) bean); 7)initMessageSource(); 初始化MessageSource组件(做国际化功能、消息绑定、消息解析) ; 1)、看容器中是否有id为messageSource的,类型是MessageSource的组件 如果有赋值给messageSource,如果没有自己创建一个DelegatingMessageSource; MessageSource:取出国际化配置文件中的某个key的值;能按照区域信息获取; 2)、把创建好的MessageSource注册在容器中,以后获取国际化配置文件的值的时候,可以自动注入MessageSource; beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource); MessageSource.getMessage(String code, Object[] args, String defaultMessage, Locale locale); 8)initApplicationEventMulticaster(); 初始化事件派发器; 1)先去容器中查找ID为 "applicationEventMulticaster" 的组件 2)如果没有这初始化创建多播器 ,并加到容器中,就可以在其他组件需要派发事件时,自动注入这个 applicationEventMulticaster this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory); 9)onRefresh(); 子类重写这个方法,在容器刷新的时候可以自定义逻辑; 10)registerListeners(); 注册事件监听器; 1)从容器中拿到所有的监听器 ApplicationListener.class String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false); 2)把他们注册到 applicationEventMulticaster (事件多播器)中 getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName); 3)派发之前步骤产生的事件; this.earlyApplicationEvents getApplicationEventMulticaster().multicastEvent(earlyEvent); 11)finishBeanFactoryInitialization(beanFactory); 初始化剩下的单实例bean beanFactory.preInstantiateSingletons(); 初始化后剩下的单实例bean 1)获取容器中所有的bean,依次进行初始化和创建对象 2)获取bean的定义信息 RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName); 3)bean不是抽象的,是单实例,不是懒加载的 if(!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) 1)判断是否是FactoryBean;是否是实现FactoryBean接口的Bean;是则为FactoryBean创建bean,使用其getObject()返回的bean if (isFactoryBean(beanName)) 2)不是FactoryBean,利用getBean(beanName);创建对象 4)利用getBean(beanName) -> doGetBean() ;创建对象 1)getSingleton(beanName); 先获取缓存中保存的单实例bean,如果能获取到说明这个bean之前被创建过(所有创建过的单实例Bean都会被缓存起来) 【三级缓存】 this.singletonObjects.get(beanName); -> Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256); —> 单例对象的缓存:Cache of singleton objects 2)缓存中获取不到,开始bean的创建过程 3)markBeanAsCreated(beanName); 首先标记当前bean已经被创建,保证bean的单例; 4)获取bean的定义信息;RootBeanDefinition 5)获取当前bean依赖的其他bean;如果有按照getBean()把依赖的bean先创建出来; 6)启动单实例bean的创建流程 createBean(beanName, mbd, args); 1)Object bean = resolveBeforeInstantiation(beanName, mbdToUse); 让BeanPostProcessor先拦截【InstantiationAwareBeanPostProcessor】,返回代理对象【AOP自动配置开启原理】 先触发:postProcessBeforeInstantiation(); 如果有返回值:触发postProcessAfterInitialization(); 2)如果步骤1,有代理返回值,则直接返回;否则调用步骤3 3) Object beanInstance = doCreateBean(beanName, mbdToUse, args); 1)【创建bean实例】;createBeanInstance(beanName, mbd, args); 利用工厂方法或者对象的构造器 2)applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); 调用 MergedBeanDefinitionPostProcessor -> postProcessMergedBeanDefinition() 3)【bean属性赋值】上述对bean进行实例化了,但是bean并没有具体的属性值 populateBean(beanName, mbd, instanceWrapper); 1)赋值之前 hasInstantiationAwareBeanPostProcessors() 判断是否为 InstantiationAwareBeanPostProcessor InstantiationAwareBeanPostProcessor -> postProcessAfterInstantiation() 2)再次拿到 InstantiationAwareBeanPostProcessor 后置处理器 调用 postProcessProperties() 、 postProcessPropertyValues() 方法 获取bean属性的值 =====赋值之前:=== 3)应用bean属性的值:为属性利用setter方法进行赋值 applyPropertyValues(beanName, mbd, bw, pvs); 4)【bean初始化】 initializeBean(beanName, exposedObject, mbd); 1)【执行Aware接口方法】执行部分xxxAware接口的方法; invokeAwareMethods(beanName, bean); BeanNameAware、BeanClassLoaderAware、BeanFactoryAware 2)【执行后置处理器之前方法】 applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName); BeanPostProcessor -> postProcessBeforeInitialization(result, beanName); 3) 【执行初始化方法】invokeInitMethods(beanName, wrappedBean, mbd); 1)bean是否是 InitializingBean 接口的实现;是执行接口规定的初始化方法 ((InitializingBean) bean).afterPropertiesSet(); 2)是否自定义初始化方法; getInitMethodName(); 4)【执行后置处理器之后方法】applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName); BeanPostProcessor -> postProcessAfterInitialization(result, beanName); 5)注册bean的销毁方法;registerDisposableBeanIfNecessary(beanName, bean, mbd); DisposableBeanAdapter -> DisposableBean 7)将创建的bean添加到缓存中 singletonObjects getSingleton() -> addSingleton(beanName, singletonObject); ioc容器就是这些map;很多的map里面保存了单实例beans,环境信息.... 5)所有的bean都利用getBean()创建完成后,检查所有bean是否是 SmartInitializingSingleton 接口的bean 是的话执行: org.springframework.beans.factory.SmartInitializingSingleton -> afterSingletonsInstantiated() 12)finishRefresh(); 完成BeanFactory的初始化创建工作;IOC容器创建完成; 1)clearResourceCaches(); 清除上下文级别的资源缓存(如扫描中的ASM元数据) 2)initLifecycleProcessor(); 初始化和生命周期有关的后置处理器; LifecycleProcessor 默认从容器中找是否有lifecycleProcessor的组件【LifecycleProcessor】;如果没有new DefaultLifecycleProcessor(),加入到容器; LifecycleProcessor -> void onRefresh(); / void onClose(); 3) getLifecycleProcessor().onRefresh(); 获取前面的生命周期处理器,回调其onRefresh()方法 4)publishEvent(new ContextRefreshedEvent(this)); 发布容器刷新完成事件; 5)LiveBeansView.registerApplicationContext(this); 注册MBean
1)Spring容器在启动的时候,会先保存所有注册进来的bean的定义信息
2)Spring容器会在合适的时机创建这些Bean
3)后置处理器:
4)事件驱动模型;
InitializingSingleton 接口的bean
是的话执行: org.springframework.beans.factory.SmartInitializingSingleton -> afterSingletonsInstantiated()
12)finishRefresh(); 完成BeanFactory的初始化创建工作;IOC容器创建完成;
1)clearResourceCaches(); 清除上下文级别的资源缓存(如扫描中的ASM元数据)
2)initLifecycleProcessor(); 初始化和生命周期有关的后置处理器; LifecycleProcessor
默认从容器中找是否有lifecycleProcessor的组件【LifecycleProcessor】;如果没有new DefaultLifecycleProcessor(),加入到容器;
LifecycleProcessor -> void onRefresh(); / void onClose();
3) getLifecycleProcessor().onRefresh(); 获取前面的生命周期处理器,回调其onRefresh()方法
4)publishEvent(new ContextRefreshedEvent(this)); 发布容器刷新完成事件;
5)LiveBeansView.registerApplicationContext(this); 注册MBean
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。