博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring Ioc 源码分析(二)- bean的实例化
阅读量:6334 次
发布时间:2019-06-22

本文共 24032 字,大约阅读时间需要 80 分钟。

hot3.png

在  中,我们完成了从 xml 到 BeanDefinition的过程。只是把 xml描述的 Bean定义转换为 Java对象描述。本文将讲解 spring 如何利用 BeanDefinition 完成bean的实例化,最终供客户端使用。

首先是看下利用Class类型,返回对应的Bean:

BeanService beanService = beanFactory.getBean(BeanService.class);		beanService.doSomething();
/**     *   门面方法     */    @Override	public 
T getBean(Class
requiredType) throws BeansException { return getBean(requiredType, (Object[]) null); }
@Override	@SuppressWarnings("unchecked")	public 
T getBean(Class
requiredType, Object... args) throws BeansException { Assert.notNull(requiredType, "Required type must not be null"); // 根据所需的Class计算出候补BeanName列表 String[] candidateNames = getBeanNamesForType(requiredType); if (candidateNames.length > 1) { List
autowireCandidates = new ArrayList
(candidateNames.length); for (String beanName : candidateNames) { if (!containsBeanDefinition(beanName) || getBeanDefinition(beanName).isAutowireCandidate()) { autowireCandidates.add(beanName); } } if (autowireCandidates.size() > 0) { candidateNames = autowireCandidates.toArray(new String[autowireCandidates.size()]); } } // 候选BeanName为一个 if (candidateNames.length == 1) { return getBean(candidateNames[0], requiredType, args); } // 多个候补BeanName, 需要比较优先级 else if (candidateNames.length > 1) { Map
candidates = new LinkedHashMap
(); for (String beanName : candidateNames) { // 每个Bean都实例化,并把 对象放到 临时 Map中 candidates.put(beanName, getBean(beanName, requiredType, args)); } // 决定哪个 String primaryCandidate = determinePrimaryCandidate(candidates, requiredType); if (primaryCandidate != null) { // 不为空,表示有候补BeanName胜出,直接返回临时Map中的对象 return (T) candidates.get(primaryCandidate); } String priorityCandidate = determineHighestPriorityCandidate(candidates, requiredType); if (priorityCandidate != null) { return (T) candidates.get(priorityCandidate); } throw new NoUniqueBeanDefinitionException(requiredType, candidates.keySet()); } BeanFactory parent = getParentBeanFactory(); if (parent != null) { return parent.getBean(requiredType, args); } throw new NoSuchBeanDefinitionException(requiredType); }
/**	 * 门面方法	 */	public 
T getBean(String name, Class
requiredType, Object... args) throws BeansException { return doGetBean(name, requiredType, args, false); }

从命名中也可以看到,doGetBean 是真正 获取 Bean 的方法: 

protected 
T doGetBean( final String name, final Class
requiredType, final Object[] args, boolean typeCheckOnly) throws BeansException { final String beanName = transformedBeanName(name); Object bean; // 检查缓存中是否有 // 因为spring在创建单例的时候,会存在依赖注入的情况 // 为了避免依赖注入是发生循环依赖问题,spring 会把创建 Bean 的 ObjectFactory // 提早曝光,也就是把ObjectFactory 加入到缓存中 Object sharedInstance = getSingleton(beanName); if (sharedInstance != null && args == null) { if (logger.isDebugEnabled()) { if (isSingletonCurrentlyInCreation(beanName)) { logger.debug("Returning eagerly cached instance of singleton bean '" + beanName + "' that is not fully initialized yet - a consequence of a circular reference"); } else { logger.debug("Returning cached instance of singleton bean '" + beanName + "'"); } } bean = getObjectForBeanInstance(sharedInstance, name, beanName, null); } else { // 单例才会解决循环依赖,原型模式直接抛出异常 if (isPrototypeCurrentlyInCreation(beanName)) { throw new BeanCurrentlyInCreationException(beanName); } // 当前BeanFactory 不包含 名为beanName 的 bean // 那么从父类加载 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 , 用户注册的bean, 配置解析完成之后,都是 GernericBeanDefinition // GernericBeanDefinition 中可以指定 父BeanDefinition // spring 用的是 RootBeanDefinition,即把 父子BeanDefinition 合并过后的 BeanDefinition // 可以看到 RootBeanDefinition 的 getParentName 写死返回 null final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); checkMergedBeanDefinition(mbd, beanName, args); // 存在依赖的话,先创建依赖的bean实例 String[] dependsOn = mbd.getDependsOn(); if (dependsOn != null) { for (String dependsOnBean : dependsOn) { if (isDependent(beanName, dependsOnBean)) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Circular depends-on relationship between '" + beanName + "' and '" + dependsOnBean + "'"); } registerDependentBean(dependsOnBean, beanName); getBean(dependsOnBean); } } // 这一步开始创建本身的bean实例 // 先处理单例 if (mbd.isSingleton()) { sharedInstance = getSingleton(beanName, new ObjectFactory
() { @Override public Object getObject() throws BeansException { try { return createBean(beanName, mbd, args); } catch (BeansException ex) { destroySingleton(beanName); throw ex; } } }); bean = 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); } bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd); } else { // 自定义 模式 // 这里是一个扩展点 String scopeName = mbd.getScope(); final 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, new ObjectFactory() { @Override public Object getObject() throws BeansException { beforePrototypeCreation(beanName); try { return createBean(beanName, mbd, args); } finally { afterPrototypeCreation(beanName); } } }); bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd); } catch (IllegalStateException ex) { throw new BeanCreationException(beanName, "Scope '" + scopeName + "' is not active for the current thread; consider " + "defining a scoped proxy for this bean if you intend to refer to it from a singleton", ex); } } } catch (BeansException ex) { cleanupAfterBeanCreationFailure(beanName); throw ex; } } // 检查一下是否需要类型转换 if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) { try { return getTypeConverter().convertIfNecessary(bean, requiredType); } catch (TypeMismatchException ex) { if (logger.isDebugEnabled()) { logger.debug("Failed to convert bean '" + name + "' to required type [" + ClassUtils.getQualifiedName(requiredType) + "]", ex); } throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass()); } } return (T) bean; }
/**     *   利用线程变量,存储正在创建的原型beanName     *   用于依赖循环检查     */	protected void beforePrototypeCreation(String beanName) {		Object curVal = this.prototypesCurrentlyInCreation.get();		if (curVal == null) {         // 之所以用String 和 Set 两张类型是因为绝大多数 Prototype 模式         // 是一种轻量级的Bean,基本上很少会有依赖,要不然也不会每次请求都创建一个对象         // 所以一般都只会存自己的Bean到 线程副本中			this.prototypesCurrentlyInCreation.set(beanName);		}        // 处理多个		else if (curVal instanceof String) {			Set
beanNameSet = new HashSet
(2); beanNameSet.add((String) curVal); beanNameSet.add(beanName); this.prototypesCurrentlyInCreation.set(beanNameSet); } else { Set
beanNameSet = (Set
) curVal; beanNameSet.add(beanName); } }
/**     *   清理线程副本变量     */    protected void afterPrototypeCreation(String beanName) {		Object curVal = this.prototypesCurrentlyInCreation.get();		if (curVal instanceof String) {			this.prototypesCurrentlyInCreation.remove();		}		else if (curVal instanceof Set) {			Set
beanNameSet = (Set
) curVal; beanNameSet.remove(beanName); if (beanNameSet.isEmpty()) { this.prototypesCurrentlyInCreation.remove(); } } }

可以说doGetBean方法做了相当多的事情,各种外部依赖检查,循环依赖检查。当外部环境都创造好的时候,相对而言就简单了,这个时候就是去创建自身的实例了,即 createBean

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory

protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException {		if (logger.isDebugEnabled()) {			logger.debug("Creating instance of bean '" + beanName + "'");		}		RootBeanDefinition mbdToUse = mbd;		// 根据 BeanDefinition 中描述的 class, 加载 Class对象        // 同时clone一份 BeanDefinition ,不能修改原来的 BeanDefinition        // 防止动态类		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 { // 看是否有 InstantiationAwareBeanPostProcessor 能够直接返回实例 // 这个在什么情况下特别有用 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); } // 没有短路操作,调用正常的创建Bean逻辑 Object beanInstance = doCreateBean(beanName, mbdToUse, args); if (logger.isDebugEnabled()) { logger.debug("Finished creating instance of bean '" + beanName + "'"); } return beanInstance; }

 在实例化之前利用 InstantiationAwareBeanPostProcessor 来截断操作,看是否可以直接返回Bean。

/**	 *  short-cut 捷径创建实例检查	 */	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); if (bean != null) { // 如果InstantiationAwareBeanPostProcessor 返回值了(相当于实例化了) // 利用BeanPostProcessor处理该对象值 bean = applyBeanPostProcessorsAfterInitialization(bean, beanName); } } } mbd.beforeInstantiationResolved = (bean != null); } return bean; }

正如spring一如既往的风格,createBean最后交给了 doCreateBean来完成 真正的创建工作:

/**	 * 创建实例方法	 */	protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) {		BeanWrapper instanceWrapper = null;		if (mbd.isSingleton()) {			instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);		}		if (instanceWrapper == null) {            // 真正的创建实例方法,使用工厂方法(factory-method),构造函数注入,或使用 实例化策略实例化            // 此时只有光溜溜的一个Bean,没有任何BeanDifinition里面配置的 PropertyValues 注入进去            // 这里只所以使用BeanWrapper 保证也是因为,spring底层都是利用 BeanWrapper完成配置的属性            // 和真实对象的绑定。            // 可以参考 spring data binder			instanceWrapper = createBeanInstance(beanName, mbd, args);		}		final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);		Class
beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null); // MergedBeanDefinitionPostProcessor 合并 BeanDefinition // 这里的 BeanDefinition 是 createBean方法中 clone原始的 BeanDefinition // 衍生出来的 // Autowire 就是通过此方法实现 类型等的预处理 synchronized (mbd.postProcessingLock) { if (!mbd.postProcessed) { applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); mbd.postProcessed = true; } } // 是否需要提前曝光,单例&运行循环依赖&当前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"); } // 避免循环依赖,将 ObjectFactory 提前曝光,加入到缓存中 // 参考 doGetBean 一开始的 缓存检查 addSingletonFactory(beanName, new ObjectFactory() { @Override public Object getObject() throws BeansException { return getEarlyBeanReference(beanName, mbd, bean); } }); } Object exposedObject = bean; try { //属性注入,把 PropertyValues 注入到 Bean中,可能需要依赖其他Bean //RuntimeReference populateBean(beanName, mbd, instanceWrapper); if (exposedObject != null) { // 初始化 exposedObject = initializeBean(beanName, exposedObject, mbd); } } catch (Throwable ex) { if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) { throw (BeanCreationException) ex; } else { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex); } } //循环依赖处理 if (earlySingletonExposure) { Object earlySingletonReference = getSingleton(beanName, false); if (earlySingletonReference != null) { if (exposedObject == bean) { exposedObject = earlySingletonReference; } else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) { String[] dependentBeans = getDependentBeans(beanName); Set
actualDependentBeans = new LinkedHashSet
(dependentBeans.length); for (String dependentBean : dependentBeans) { if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) { actualDependentBeans.add(dependentBean); } } if (!actualDependentBeans.isEmpty()) { throw new BeanCurrentlyInCreationException(beanName, "Bean with name '" + beanName + "' has been injected into other beans [" + StringUtils.collectionToCommaDelimitedString(actualDependentBeans) + "] in its raw version as part of a circular reference, but has eventually been " + "wrapped. This means that said other beans do not use the final version of the " + "bean. This is often the result of over-eager type matching - consider using " + "'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example."); } } } } // 关闭方法-只对单例生效 try { registerDisposableBeanIfNecessary(beanName, bean, mbd); } catch (BeanDefinitionValidationException ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex); } return exposedObject; }

 实例化工作:

protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) {		// 类型确定		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, 则 FactoryMethod 优先 if (mbd.getFactoryMethodName() != null) { return instantiateUsingFactoryMethod(beanName, mbd, args); } boolean resolved = false; boolean autowireNecessary = false; if (args == null) { synchronized (mbd.constructorArgumentLock) {          //一个类有多个构造函数,一个构造函数有多个参数,锁定构造函数 if (mbd.resolvedConstructorOrFactoryMethod != null) { resolved = true; autowireNecessary = mbd.constructorArgumentsResolved; } } }     // 已经解析过就不用啦 if (resolved) { if (autowireNecessary) {          // 构造函数注入 return autowireConstructor(beanName, mbd, null, null); } else {          // 默认处理 return instantiateBean(beanName, mbd); } } //否则就需要去解析构造函数 Constructor
[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);     // 解析到了就用 构造函数注入 if (ctors != null || mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR || mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) { return autowireConstructor(beanName, mbd, ctors, args); } // 否则还是默认处理 return instantiateBean(beanName, mbd); }

属性注入工作:

*/	protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {		PropertyValues pvs = mbd.getPropertyValues();		if (bw == null) {			if (!pvs.isEmpty()) {				throw new BeanCreationException(						mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");			}			else {				// Skip property population phase for null instance.				return;			}		}		// InstantiationAwareBeanPostProcessor 过滤下是否需要下一步注入 PropertyValues		boolean continueWithPropertyPopulation = true;		if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {			for (BeanPostProcessor bp : getBeanPostProcessors()) {				if (bp instanceof InstantiationAwareBeanPostProcessor) {					InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;					if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {						continueWithPropertyPopulation = false;						break;					}				}			}		}          // 如果InstantiationAwareBeanPostProcessor告诉不需要了,就直接不做初始化工作了		if (!continueWithPropertyPopulation) {			return;		}     // 根据注入类型处理		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);     //InstantiationAwareBeanPostProcessor  注入一些额外的 PropertyValues		if (hasInstAwareBpps || needsDepCheck) {			PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);			if (hasInstAwareBpps) {				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);			}		}          // 实施注入		applyPropertyValues(beanName, mbd, bw, pvs);	}

初始化工作:

protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {		if (System.getSecurityManager() != null) {			AccessController.doPrivileged(new PrivilegedAction() {				@Override				public Object run() {					invokeAwareMethods(beanName, bean);					return null;				}			}, getAccessControlContext());		}		else {       // 调用Aware接口			invokeAwareMethods(beanName, bean);		}		Object wrappedBean = bean;		if (mbd == null || !mbd.isSynthetic()) {            // 调用 BeanPostPrpcessor 的 postProcessBeforeInitialization 处理下            // 如创建代理,事务管理什么的都是基于这个实现的。            // 非常非常重要			wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);		}		try {            // 调用初始化方法 			invokeInitMethods(beanName, wrappedBean, mbd);		}		catch (Throwable ex) {			throw new BeanCreationException(					(mbd != null ? mbd.getResourceDescription() : null),					beanName, "Invocation of init method failed", ex);		}		if (mbd == null || !mbd.isSynthetic()) {            // 调用 BeanPostPrpcessor 的 postProcessAfterInitialization			wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);		}		return wrappedBean;	}

Aware 接口,做一些初始化准备: 

private void invokeAwareMethods(final String beanName, final Object bean) {		if (bean instanceof Aware) {			if (bean instanceof BeanNameAware) {				((BeanNameAware) bean).setBeanName(beanName);			}			if (bean instanceof BeanClassLoaderAware) {				((BeanClassLoaderAware) bean).setBeanClassLoader(getBeanClassLoader());			}			if (bean instanceof BeanFactoryAware) {				((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);			}		}	}

初始化方法的调用: 

protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd)			throws Throwable {        // 如果是 InitializingBean ,调用它的 afterPropertiesSet 方法		boolean isInitializingBean = (bean instanceof InitializingBean);		if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {			if (logger.isDebugEnabled()) {				logger.debug("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");			}			if (System.getSecurityManager() != null) {				try {					AccessController.doPrivileged(new PrivilegedExceptionAction() {						@Override						public Object run() throws Exception {							((InitializingBean) bean).afterPropertiesSet();							return null;						}					}, getAccessControlContext());				}				catch (PrivilegedActionException pae) {					throw pae.getException();				}			}			else {				((InitializingBean) bean).afterPropertiesSet();			}		}		if (mbd != null) {            // 调用 自定义的 init-method			String initMethodName = mbd.getInitMethodName();			if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&					!mbd.isExternallyManagedInitMethod(initMethodName)) {				invokeCustomInitMethod(beanName, bean, mbd);			}		}	}

不知道看BeanFactory这个类的注释发现没,spring对一个bean的生命周期做了如下描述:

Bean factory implementations should support the standard bean lifecycle interfaces as far as possible. The full set of initialization methods and their standard order is:

1. BeanNameAware's setBeanName
2. BeanClassLoaderAware's setBeanClassLoader
3. BeanFactoryAware's setBeanFactory

4. EnvironmentAware's setEnvironment 

5. EmbeddedValueResolverAware's setEmbeddedValueResolver 
6. ResourceLoaderAware's setResourceLoader (only applicable when running in an application context)
7. ApplicationEventPublisherAware's setApplicationEventPublisher (only applicable when running in an application context)
8. MessageSourceAware's setMessageSource (only applicable when running in an application context)
9. ApplicationContextAware's setApplicationContext (only applicable when running in an application context)
10. ServletContextAware's setServletContext (only applicable when running in a web application context)

11. postProcessBeforeInitialization methods of BeanPostProcessors

12. InitializingBean's afterPropertiesSet
13. a custom init-method definition
14. postProcessAfterInitialization methods of BeanPostProcessors 

貌似4-10中没有我们想看到的Aware啊,spring是怎么实现的呢,答案正是 BeanPostProcessor

在不同的环境下,spring 为注册了不同的 BeanPostProcessor,同时为 BeanPostProcessors 处理顺序。就保证了上诉生命周期的实现。

至此, DefaultListableBeanFactory 创建Bean的步骤完成。

转载于:https://my.oschina.net/u/206123/blog/1553564

你可能感兴趣的文章
ubuntu下,py2,py3共存,/usr/bin/python: No module named virtualenvwrapper错误解决方法
查看>>
Ext.form.field.Number numberfield
查看>>
Linux文件夹分析
查看>>
解决部分月份绩效无法显示的问题:timestamp\union al\autocommit等的用法
查看>>
nginx 域名跳转 Nginx跳转自动到带www域名规则配置、nginx多域名向主域名跳转
查看>>
man openstack >>1.txt
查看>>
linux几大服务器版本大比拼
查看>>
在BT5系统中安装postgresQL
查看>>
【Magedu】Week01
查看>>
写给MongoDB开发者的50条建议Tip25
查看>>
为什么要让带宽制约云计算发展
查看>>
[iOS Animation]-CALayer 绘图效率
查看>>
2012-8-5
查看>>
VS中ProjectDir的值以及$(ProjectDir)../的含义
查看>>
我的友情链接
查看>>
PHP实现排序算法
查看>>
Business Contact Mnanager for Outlook2010
查看>>
9种用户体验设计的状态是必须知道的(五)
查看>>
解决WIN7下组播问题
查看>>
陈松松:视频营销成交率低,这三个因素没到位
查看>>