Spring5源码 - 07 Spring Bean 生命周期流程 源码解读02

文章目录

Spring5源码 - 07 Spring Bean 生命周期流程 源码解读02


Pre

Spring5源码 - 06 Spring Bean 生命周期流程 概述 01

接上文

通俗流程

下面说个比较常见的主干流程

  1. 实例化Bean对象,这个时候Bean的对象是非常低级的,基本不能够使用,因为连最基本的属性都没有设置,可以理解为
    连Autowired注解都是没有解析的;
  2. 填充属性,当做完这一步,Bean对象基本是完整的了,可以理解为Autowired注解已经解析完毕,依赖注入完成了;
  3. 如果Bean实现了BeanNameAware接口,则调用setBeanName方法;
  4. 如果Bean实现了BeanClassLoaderAware接口,则调用setBeanClassLoader方法;
  5. 如果Bean实现了BeanFactoryAware接口,则调用setBeanFactory方法;
  6. 调用BeanPostProcessor的postProcessBeforeInitialization方法;
  7. 如果Bean实现了InitializingBean接口,调用afterPropertiesSet方法;
  8. 如果Bean定义了init-method方法,则调用Bean的init-method方法;
  9. 调用BeanPostProcessor的postProcessAfterInitialization方法;当进行到这一步,Bean已经被准备就绪了,一直停留在应用的
    上下文中,直到被销毁;
  10. 如果应用的上下文被销毁了,如果Bean实现了DisposableBean接口,则调用destroy方法,如果Bean定义了destory-method
    声明了销毁方法也会被调用。

finishBeanFactoryInitialization

完成Bean的初始化

/**
	 * Finish the initialization of this context's bean factory,
	 * initializing all remaining singleton beans.
	 */
	protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
		// bean工厂创建类型转化器  Convert
		/**
		 * public class String2DateConversionService implements Converter<String,Date> {

		 	public Date convert(String source) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					try {
						return sdf.parse(source);
					} catch (ParseException e) {
					return null;
				}
		 	}
		 }

		 @Bean
		 public ConversionServiceFactoryBean conversionService() {
		 	ConversionServiceFactoryBean factoryBean = new ConversionServiceFactoryBean();
		 	Set<Converter> converterSet = new HashSet<Converter>();
		 	converterSet.add(new String2DateConversionService());
		 	factoryBean.setConverters(converterSet);
		 	return factoryBean;
		 }
		 ConversionServiceFactoryBean conversionServiceFactoryBean = (ConversionServiceFactoryBean) ctx.getBean(ConversionServiceFactoryBean.class);
		 conversionServiceFactoryBean.getObject().convert("2019-06-03 12:00:00",Date.class)
		 */
		if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
				beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
			beanFactory.setConversionService(
					beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
		}

		/**
		 * public class MainConfig implements EmbeddedValueResolverAware{
		 *
		 *     public void setEmbeddedValueResolver(StringValueResolver resolver) {
		 		this.jdbcUrl = resolver.resolveStringValue("${ds.jdbcUrl}");
		 		this.classDriver = resolver.resolveStringValue("${ds.classDriver}");
		      }
		 }
		 */
		if (!beanFactory.hasEmbeddedValueResolver()) {
			beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
		}

		// 处理aspectj
		String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
		for (String weaverAwareName : weaverAwareNames) {
			getBean(weaverAwareName);
		}

		// Stop using the temporary ClassLoader for type matching.
		beanFactory.setTempClassLoader(null);

		//冻结所有的 bean 定义 , 说明注册的 bean 定义将不被修改或任何进一步的处理
		beanFactory.freezeConfiguration();

		//实例化剩余的单实例bean
		beanFactory.preInstantiateSingletons();
	}

继续

beanFactory.preInstantiateSingletons();
@Override
	public void preInstantiateSingletons() throws BeansException {
		if (logger.isDebugEnabled()) {
			logger.debug("Pre-instantiating singletons in " + this);
		}

		//获取我们容器中所有bean定义的名称
		List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);

		//循环我们所有的bean定义名称
		for (String beanName : beanNames) {
			//合并我们的bean定义
			RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
			/**
			 * 根据bean定义判断是不是抽象的&& 不是单例的 &&不是懒加载的
			 */
			if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
				//是不是工厂bean
				if (isFactoryBean(beanName)) {
					//是的话 给beanName+前缀&符号
					Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
					if (bean instanceof FactoryBean) {
						final 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());
						}
						//调用真正的getBean的流程
						if (isEagerInit) {
							getBean(beanName);
						}
					}
				}
				else {//非工厂Bean 就是普通的bean
					getBean(beanName);
				}
			}
		}

		//或有的bean的名称 ...........到这里所有的单实例的bean已经记载到单实例bean到缓存中
		for (String beanName : beanNames) {
			//从单例缓存池中获取所有的对象
			Object singletonInstance = getSingleton(beanName);
			//判断当前的bean是否实现了SmartInitializingSingleton接口
			if (singletonInstance instanceof SmartInitializingSingleton) {
				final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
				if (System.getSecurityManager() != null) {
					AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
						smartSingleton.afterSingletonsInstantiated();
						return null;
					}, getAccessControlContext());
				}
				else {
					//触发实例化之后的方法afterSingletonsInstantiated
					smartSingleton.afterSingletonsInstantiated();
				}
			}
		}
	}

重点方法肯定是 getBean(beanName);

Spring5源码 - 07 Spring Bean 生命周期流程 源码解读02
Spring5源码 - 07 Spring Bean 生命周期流程 源码解读02

上一篇:策略模式+工厂模式代替if else 循环


下一篇:关于lr调用jar在vuser中可以运行,但是controller中却报错的问题