一、初始化流程
spring容器启动时,会实例化非懒加载的bean实例,将bean实例交给spring容器管理,避免程序中通过new关键字创建。bean的初始化主要分为4个步骤:1)从缓存中查找;2)创建bean实例并完成自动装配;3)执行初始化方法;4)将bean放入缓存。具体流程如图所示:
1)从缓存map中以beanName为key查找bean实例,若存在,则返回缓存中的实例;
2)判断当前spring容器是否加载了该benaName对应的BeanDefinition,若不存在,则交给父容器处理(如spring为spring mvc的父容器);
3)合并BeanDefinition,递归调用,从父bean中继承PropertyValues、自动装配方式等,此步骤后,bean中的PropertyValues包含父bean中定义的PropertyValues;
4)执行InstantiationAwareBeanPostProcessor扩展点的前置方法,若前置方法返回的对象不为空,则执行BeanPostProcessor的后置方法,返回前置方法返回的实例,并将器缓存到spring容器(如实现AOP的关键类AbstractAutoProxyCreator);
5)创建BeanWrapper实例(Bean的装饰类),先判断是否配置factory-method工厂方法,如果有配置,则调用工厂方法创建BeanWrapper,否则调用SmartInstantiationAwareBeanPostProcessor扩展点的determineCandidateConstructors()方法找到类的构造方法,通过反射创建BeanWrapper实例;
6)执行MergedBeanDefinitionPostProcessor扩展点的postProcessMergedBeanDefinition()方法,加载类中@Autowired、@Value、@PostConstruct等注解,并将其放入缓存;
7)如果支持循环引用,则将未完成装配等bean实例放入第三级缓存(解决循环依赖);
8)自动装配,填充依赖,此时装配的是PropertyValues中的属性,@Autowired、@Value装配不在此步骤执行;
9)执行初始化方法,先执行Aware接口的方法,再执行BeanPostProcessor扩展点的postProcessBeforeInitialization()前置方法,如@Autowired、@Value、@PostConstruct,再执行InitializingBean接口的afterPropertiesSet()方法,最后执行init-method指定的方法;
10)执行BeanPostProcessor扩展点的后置方法;
11)将bean实例方法spring容器缓存。
二、bean初始化源码分析
spring容器刷新上下文事件时,当定义得bean元数据及BeanPostProcessor初始化完成后,便会对非懒加载对bean进行初始化。
1)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(); // 初始化非懒加载对bean. 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(); } } } protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) { // Initialize conversion service for this context. 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)); } // Register a default embedded value resolver if no bean post-processor // (such as a PropertyPlaceholderConfigurer bean) registered any before: // at this point, primarily for resolution in annotation attribute values. if (!beanFactory.hasEmbeddedValueResolver()) { beanFactory.addEmbeddedValueResolver(new StringValueResolver() { @Override public String resolveStringValue(String strVal) { return getEnvironment().resolvePlaceholders(strVal); } }); } 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); // Allow for caching all bean definition metadata, not expecting further changes. beanFactory.freezeConfiguration(); // 真正初始化非懒加载对bean实例 beanFactory.preInstantiateSingletons(); }
2)DefaultListableBeanFactory#preInstantiateSingletons()初始化非懒加载对bean:
public void preInstantiateSingletons() throws BeansException { if (this.logger.isDebugEnabled()) { this.logger.debug("Pre-instantiating singletons in " + this); } ListbeanNames = new ArrayList (this.beanDefinitionNames); // Trigger initialization of all non-lazy singleton beans... // 循环spring容器中对bean for (String beanName : beanNames) { RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName); // 非抽象类&单例&非懒加载 if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) { // 如果bean是FactoryBean,则为beanName加上前缀"&",表示获取FactoryBean本身 if (isFactoryBean(beanName)) { final FactoryBean factory = (FactoryBean ) getBean(FACTORY_BEAN_PREFIX + beanName); boolean isEagerInit; if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) { isEagerInit = AccessController.doPrivileged(new PrivilegedAction () @Override public Boolean run() { return ((SmartFactoryBean ) factory).isEagerInit(); } }, getAccessControlContext()); } else { isEagerInit = (factory instanceof SmartFactoryBean && ((SmartFactoryBean ) factory).isEagerInit()); } if (isEagerInit) { getBean(beanName); } } else { // 实例化Bean getBean(beanName); } } }
3)AbstractBeanFactory#doGetBean(),该方法会先从缓存中查找bean,若存在,则返回缓存中的bean,否则走实例化bean流程
protectedT doGetBean( final String name, final Class requiredType, final Object[] args, boolean typeCheckOnly) throws BeansException { final String beanName = transformedBeanName(name); Object bean; // Eagerly check singleton cache for manually registered singletons. // 从缓存中查找bean,若缓存中存在,则返回缓存中的bean,此处也是解决循环依赖的方法 Object sharedInstance = getSingleton(beanName); if (sharedInstance != null && args == null) { bean = getObjectForBeanInstance(sharedInstance, name, beanName, null); } else { BeanFactory parentBeanFactory = getParentBeanFactory(); // 到父容器查找 if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { // Not found -> check parent. String nameToLookup = originalBeanName(name); if (args != null) { // Delegation to parent with explicit args. return (T) parentBeanFactory.getBean(nameToLookup, args); } else { // No args -> delegate to standard getBean method. return parentBeanFactory.getBean(nameToLookup, requiredType); } } if (!typeCheckOnly) { markBeanAsCreated(beanName); } try { // 合并BeanDefinition,如设置了 的场景,使用递归方法从父BeanDefinition中 // 继承PropertyValues等,此步骤后,bean中的PropertyValues包含父bean中定义的PropertyValues final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); checkMergedBeanDefinition(mbd, beanName, args); // 省略部分代码 if (mbd.isSingleton()) { sharedInstance = getSingleton(beanName, new ObjectFactory
4)AbstractAutowireCapableBeanFactory#createBean(),该方法会先交给实现了InstantiationAwareBeanPostProcessor接口的扩展点一个返回bean实例的机会
protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) { RootBeanDefinition mbdToUse = mbd; // Make sure bean class is actually resolved at this point, and // clone the bean definition in case of a dynamically resolved Class // which cannot be stored in the shared merged bean definition. Class resolvedClass = resolveBeanClass(mbd, beanName); if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) { mbdToUse = new RootBeanDefinition(mbd); mbdToUse.setBeanClass(resolvedClass); } // Prepare method overrides. try { mbdToUse.prepareMethodOverrides(); } catch (BeanDefinitionValidationException ex) { throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(), beanName, "Validation of method overrides failed", ex); } try { // 交给BeanPostProcessor扩展点执行,当返回等对象非null时,则bean初始化流程终止,如aop等代理对象 Object bean = resolveBeforeInstantiation(beanName, mbdToUse); if (bean != null) { return bean; } } catch (Throwable ex) { throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName, "BeanPostProcessor before instantiation of bean failed", ex); } Object beanInstance = doCreateBean(beanName, mbdToUse, args); if (logger.isDebugEnabled()) { logger.debug("Finished creating instance of bean '" + beanName + "'"); } return beanInstance; }
5)AbstractAutowireCapableBeanFactory#resolveBeforeInstantiation(),得到spring容器中实现了InstantiationAwareBeanPostProcessor扩展点的类,并执行扩展点的前置方法,若前置方法返回的对象不是null,则执行后置方法,且中断该bean的初始化流程
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. if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { Class targetType = determineTargetType(beanName, mbd); if (targetType != null) { // 执行实现了InstantiationAwareBeanPostProcessor接口的前置方法 bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName); // 返回bean不为空时,执行实现了InstantiationAwareBeanPostProcessor接口的后置方法 if (bean != null) { bean = applyBeanPostProcessorsAfterInitialization(bean, beanName); } } } mbd.beforeInstantiationResolved = (bean != null); } return bean; } // BeanPostProcessor前置方法 protected Object applyBeanPostProcessorsBeforeInstantiation(Class beanClass, String beanName) { for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName); if (result != null) { return result; } } } return null; } // BeanPostProcessor后置方法 public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException { Object result = existingBean; for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) { result = beanProcessor.postProcessAfterInitialization(result, beanName); if (result == null) { return result; } } return result; }
6)AbstractAutowireCapableBeanFactory#doCreateBean(),该方法是bean实例化的核心,会先创建未完成装配功能的bean,然后将bean放入缓存,接着实现自动装配,最后调用初始化方法,完成初始化bean的整个流程
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) throws BeanCreationException { // 通过BeanWrapper实例化Bean BeanWrapper instanceWrapper = null; if (mbd.isSingleton()) { instanceWrapper = this.factoryBeanInstanceCache.remove(beanName); } if (instanceWrapper == null) { // 如果在bean定义中指定了factory-method,则执行工厂方法返回bean,否则会根据 // SmartInstantiationAwareBeanPostProcessor扩展点的determineCandidateConstructors()方法, // 找到对应的构造函数,通过反射创建bean,可看源码了解具体实现思路 instanceWrapper = createBeanInstance(beanName, mbd, args); } final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null); Class beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null); mbd.resolvedTargetType = beanType; // 执行MergedBeanDefinitionPostProcessor的postProcessMergedBeanDefinition流程,将@Resource、 // @Autowired、@Value等注解加载到缓存,供后续使用 synchronized (mbd.postProcessingLock) { if (!mbd.postProcessed) { try { applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); } catch (Throwable ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Post-processing of merged bean definition failed", ex); } mbd.postProcessed = true; } } // 当bean是单例,并允许循环依赖,且bean的状态是创建状态,则将未完成装配的bean放入第三级缓存,解决循环依赖 boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && isSingletonCurrentlyInCreation(beanName)); if (earlySingletonExposure) { if (logger.isDebugEnabled()) { logger.debug("Eagerly caching bean '" + beanName + "' to allow for resolving potential circular references"); } addSingletonFactory(beanName, new ObjectFactory
7)AbstractAutowireCapableBeanFactory#createBeanInstance(),该方法是通过指定的工厂bean的方法或反射创建bean
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) { // Make sure bean class is actually resolved at this point. Class beanClass = resolveBeanClass(mbd, beanName); if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Bean class isn't public, and non-public access not allowed: " + beanClass.getName()); } // 如果指定了factory-method属性,则调用工厂方法创建bean if (mbd.getFactoryMethodName() != null) { return instantiateUsingFactoryMethod(beanName, mbd, args); } // Shortcut when re-creating the same bean... boolean resolved = false; // bean配置中是否指定了需通过带参数的构造函数创建bean boolean autowireNecessary = false; if (args == null) { synchronized (mbd.constructorArgumentLock) { if (mbd.resolvedConstructorOrFactoryMethod != null) { resolved = true; autowireNecessary = mbd.constructorArgumentsResolved; } } } if (resolved) { if (autowireNecessary) { // 根据配置的构造函数参数创建bean return autowireConstructor(beanName, mbd, null, null); } else { // 反射,调用默认构造函数创建bean return instantiateBean(beanName, mbd); } } // 如果是通过用户自定义的需创建带参数的构造函数bean,则执行SmartInstantiationAwareBeanPostProcessor // 接口的determineCandidateConstructors()方法,找到对应的构造函数 Constructor [] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName); if (ctors != null || mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR || mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) { return autowireConstructor(beanName, mbd, ctors, args); } // No special handling: simply use no-arg constructor. return instantiateBean(beanName, mbd); }
8)AbstractAutowireCapableBeanFactory#populateBean(),该方法主要是完成bean的自动装配,自动装配的方法主要有:AUTOWIRE_NO、AUTOWIRE_BY_NAME、AUTOWIRE_BY_TYPE、AUTOWIRE_CONSTRUCTOR这4种,默认是AUTOWIRE_NO不自动装配,需在bean定义中配置完成属性注入
protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) { PropertyValues pvs = mbd.getPropertyValues(); // 省略部分代码 // 自动装配,默认值为AUTOWIRE_NO if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME || mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) { MutablePropertyValues newPvs = new MutablePropertyValues(pvs); // Add property values based on autowire by name if applicable. if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) { autowireByName(beanName, mbd, bw, newPvs); } // Add property values based on autowire by type if applicable. if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) { autowireByType(beanName, mbd, bw, newPvs); } pvs = newPvs; } boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors(); boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE); if (hasInstAwareBpps || needsDepCheck) { PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching); if (hasInstAwareBpps) { // 执行InstantiationAwareBeanPostProcessor的postProcessPropertyValues()方法,将bean中 // 的@Autowired、@Value、@Resource注解通过反射的方式,注入到bean中 for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName); if (pvs == null) { return; } } } } if (needsDepCheck) { checkDependencies(beanName, mbd, filteredPds, pvs); } } // 将PropertyValues集合的值注入到bean中对应的属性中,完成属性装配 applyPropertyValues(beanName, mbd, bw, pvs); }
9)AbstractAutowireCapableBeanFactory#initializeBean(),bean创建后的初始化方法,包括执行Aware接口方法、@PostConstruct、afterProperties()及init-method方法
protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) { if (System.getSecurityManager() != null) { AccessController.doPrivileged(new PrivilegedAction
三、BeanPostProcessor扩展点
BeanPostProcessor扩展点有五个接口十个实现,具体如下图所示:
1)InstantiationAwareBeanPostProcessor:实例化bean的扩展点,Spring自带的实现类有CommonAnnotationBeanPostProcessor、AutowiredAnnotationBeanPostProcessor、RequiredAnnotationBeanPostProcessor等
1.1)postProcessBeforeInstantiation方法:在实例化目标对象之前执行,可自定义实例化逻辑,AOP返回的对象是AbstractAutoProxyCreator返回的代理对象;
1.2)postProcessAfterInstantiation方法:bean实例化完成后的操作,如果返回false,将阻止其他的InstantiationAwareBeanPostProcessor的postProcessAfterInstantiation执行;
1.3)postProcessPropertyValues方法:完成其他的定制的一些依赖注入,如AutowiredAnnotationBeanPostProcessor执行@Autowired、@Value注解,CommonAnnotationBeanPostProcessor执行@Resource等注解的注入。
2)MergedBeanDefinitionPostProcessor:合并bean定义的扩展点,Spring自带的实现类有CommonAnnotationBeanPostProcessor、AutowiredAnnotationBeanPostProcessor、RequiredAnnotationBeanPostProcessor等
2.1)postProcessMergedBeanDefinition方法:执行bean定义的合并,如将@Autowired、@Value等注解加载到缓存,供依赖注入时使用。
3)SmartInstantiationAwareBeanPostProcessor:继承InstantiationAwareBeanPostProcessor,在InstantiationAwareBeanPostProcessor接口基础上增加了3个方法,Spring自带的实现类有AspectJAwareAdvisorAutoProxyCreator、AnnotationAwareAspectJAutoProxyCreator等:
3.1)predictBeanType方法:预测Bean的类型,返回第一个预测成功的Class类型,如果不能预测返回null;调用BeanFactory.getType(name)时,通过Bean定义无法得到Bean类型信息时就调用该回调方法来决定类型信息;BeanFactory.isTypeMatch(name, targetType)用于检测给定名字的Bean是否匹配目标类型(如在依赖注入时需要使用);
3.2)determineCandidateConstructors方法:检测Bean的构造器,可以检测出多个候选构造器,再根据参数决定选择哪一个构造器,在反射创建BeanWrapper步骤使用;
3.3)getEarlyBeanReference方法:获取提早暴露的对象,即spring为了解决循环依赖,在未完成属性装配和bean初始化方法之前,就不完整的bean放入第三级缓存。
4) DestructionAwareBeanPostProcessor:销毁bean的扩展点,spring自带的实现类有InitDestroyAnnotationBeanPostProcessor:
4.1)postProcessBeforeDestruction方法:销毁后处理回调方法,该回调只能应用到单例Bean,如InitDestroyAnnotationBeanPostProcessor完成@PreDestroy注解的销毁方法调用。
5)BeanPostProcessor扩展点:该扩展点是以上4个扩展点接口的父接口,自定义的扩展点一般是实现改接口
5.1)postProcessBeforeInitialization方法:在实例化、依赖注入后,调用InitializingBean的afterPropertiesSet()方法之前执行,如@PostConstruct注解方法等,方法的返回值将替代原始的Bean对象;
5.2)postProcessAfterInitialization方法:在实例化、依赖注入、初始化完成后执行,方法的返回值将替代原始的Bean对象。