读书人

Spring Ioc 器皿 创建Bean 的流程

发布时间: 2012-11-16 14:12:15 作者: rapoo

Spring Ioc 容器 创建Bean 的流程

1、Spring 版本 3.1

?

2、BeanFactory 创建bean 流程:

?

以 DefaultListableBeanFactory 为例说明BeanFactory 创建bean的流程。 DefaultListableBeanFactory是Spring提供的两个重要的BeanFactory的实现

?

2.1、当我们调用类似 DefaultListableBeanFactory 的getBean(...) 方法时候、 会去调用其父类AbstractAutowireCapableBeanFactory 的 createBean(...) 方法:

?

2.2、 AbstractAutowireCapableBeanFactory 的 createBean 如下:

?

protected Object createBean( final String beanName, final RootBeanDefinition mbd,

??????? final Object[] args) throws BeanCreationException {

???? .... // 省略

????? // Make sure bean class is actually resolved at this point.

????? resolveBeanClass(mbd, beanName); // ????? // Prepare method overrides.

???? try {

??????? mbd.prepareMethodOverrides(); // 2.2.2 ???

???? }catch (BeanDefinitionValidationException ex) {

?????? .... // 省略

???? }

???? try {

?? // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.

??? // 2.2.3.???? Object bean = resolveBeforeInstantiation(beanName, mbd);

???? if (bean != null ) {

????? return bean; // 2.2.4.???? }

??? }catch (Throwable ex) {

???? ... // 省略

?????? }

??? Object beanInstance = doCreateBean(beanName, mbd, args);//2.2.5. ????? ... // 省略

??? return beanInstance;

??? //2.3.1、构造Bean,并返回bean 的 BeanWrapper 类

? BeanWrapper instanceWrapper = null ;

? if (mbd.isSingleton()) {

????? instanceWrapper = this .factoryBeanInstanceCache .remove(beanName);

? }

? if (instanceWrapper == null ) {

????? instanceWrapper = createBeanInstance(beanName, mbd, args);

? }

? final Object bean = (instanceWrapper != null ?instanceWrapper .getWrappedInstance(): null);

? Class beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null );

? // Allow post-processors to modify the merged bean definition.

?? //2.3.2、回调MergedBeanDefinitionPostProcessor的postProcessMergedBeanDefinition接口

? synchronized (mbd. postProcessingLock ) {

????? if (!mbd. postProcessed ) {

????????? applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);

????????? mbd. postProcessed = true ;

????? }

? }

? // Eagerly cache singletons to be able to resolve circular references

? // even when triggered by lifecycle interfaces like BeanFactoryAware.

? boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences

??????????? && isSingletonCurrentlyInCreation(beanName));

?

? if (earlySingletonExposure) {

????? // ... 省略日志

????? addSingletonFactory(beanName, new ObjectFactory() {

????????? public Object getObject() throws BeansException {

????????????????? ????????????? return getEarlyBeanReference(beanName, mbd, bean);

????????? }

????? });

? }

? // Initialize the bean instance.

? Object exposedObject = bean;

? try {

??????? ??? populateBean(beanName, mbd, instanceWrapper);

??? if (exposedObject != null ) {

??????? ??????? exposedObject = initializeBean(beanName, exposedObject, mbd);

??? }

?? } catch (Throwable ex) {

????? // ... 省略

? }

? if (earlySingletonExposure) {

????? // ... 省略部分代码, 代码用途???

? }

? // Register bean as disposable.

?

?? // 注册Bean的销毁回调

? try {

????? registerDisposableBeanIfNecessary(beanName, bean, mbd);

? } catch (BeanDefinitionValidationException ex) {

????? // ... 省略

? }

? return exposedObject;

protected voidpopulateBean(String beanName, AbstractBeanDefinition mbd,

?????????????? BeanWrapper bw) {

???? PropertyValuespvs = mbd.getPropertyValues();

???? if (bw == null) {

??????? if (!pvs.isEmpty()) {

??????????? // ... 省略

??????? }else {

???????? // Skip property population phase for null instance.

???????? return;

???? ? ?}

???? }

???? // Give any InstantiationAwareBeanPostProcessors theopportunity to modify the

???? // state of the bean before properties are set. This canbe used, for example,

???? // to support styles of field injection.

???? booleancontinueWithPropertyPopulation = true;

?

???? if (!mbd.isSynthetic()&& hasInstantiationAwareBeanPostProcessors()) {

???????? for (BeanPostProcessor bp :getBeanPostProcessors()) {

???????????? if (bp instanceofInstantiationAwareBeanPostProcessor) {

???????????????? InstantiationAwareBeanPostProcessoribp =

????????????????????????????????????? (InstantiationAwareBeanPostProcessor) bp;

???????????????? if(!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {

???????????????? ? ? continueWithPropertyPopulation= false;

???????????????????? break;

????????????????? }

???? ? ? ? ??}

????????? }

???? }

??? if(!continueWithPropertyPopulation) {

?????? return;

??? }

?

?????? ??? if(mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME||

???????? mbd.getResolvedAutowireMode()== RootBeanDefinition.AUTOWIRE_BY_TYPE) {

??????? MutablePropertyValuesnewPvs = newMutablePropertyValues(pvs);

?

?????? // Add property values based on autowire by name ifapplicable.

?????? if(mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME){

?????????? autowireByName(beanName,mbd, bw, newPvs);

?????? }

?

?????? // Add property values based on autowire by type ifapplicable.

?????? 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);

????????????? ??????? if (hasInstAwareBpps) {

????????????????? for (BeanPostProcessor bp :getBeanPostProcessors()) {

????????????? if (bp instanceofInstantiationAwareBeanPostProcessor) {

????????????????? InstantiationAwareBeanPostProcessoribp =

??????????????????????????????????????????????? (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);

?

}

?

注意: 2.4.2、 执行其它的依赖注入, 当Spring 配置文件中有<context:annotation-config/> 这样的标签,并且

????????????????????? 使用Spring 的ApplicationContext 容器(BeanFactory 不会自动注册) 会自动注册一些内置的

????????????????????? BeanPostProcessors, 这些BeanPostProcessesors 将会在此处用到,完成一些注入工作。

???????? ? ? ? ? ? ? a、AutowiredAnnotationBeanPostProcessor? 执行@Autowired注入

???????? ? ? ? ? ? ? b、CommonAnnotationBeanPostProcessor?? 执行@Resource 注入

???????????????????? c、 RequiredAnnotationBeanPostProcessor? 执行@Required 的注入检查

?

public void refresh() throws BeansException,IllegalStateException {

??????? synchronized (this.startupShutdownMonitor){

??????????? // Prepare this context for refreshing.

??????????? prepareRefresh();

?

??????????? // Tell the subclass to refresh the internal beanfactory.

??????????? ConfigurableListableBeanFactorybeanFactory = obtainFreshBeanFactory();

?

??????????? // Prepare the bean factory for use in this context.

???????????????????? // 3.2.1为BeanFactory 注册一些内部 BeanPostProcess 如

???????????????????? //? (ApplicationContextAwareProcessor)

??????????? prepareBeanFactory(beanFactory);

?

??????????? try {

??????????????? // Allows post-processing of the bean factory in contextsubclasses.

??????????????? postProcessBeanFactory(beanFactory);

?

??????????????? // Invoke factory processors registered as beans in thecontext.

?????????????? // 3.2.2 调用在配置文件中定义的 BeanFactoryPostProcessor bean 方法的 ?????????????? // postProcessBeanFactory(...) 方法

????????????????????????? invokeBeanFactoryPostProcessors(beanFactory);

?

??????????????? // Register bean processors that intercept bean creation.

?????????????????????????? // 3.2.3 注册内部的BeanPostProcessors 如有<context:annotation-config/>

?????????????????????????? // 这个标签将注册如下 BeanPostProcessors:

????????????????????????? //AutowiredAnnotationBeanPostProcessor,CommonAnnotationBeanPostProcessor

????????????????????????? //RequiredAnnotationBeanPostProcessor 等.

?????????????? registerBeanPostProcessors(beanFactory);

?

??????????????? // Initialize message source for this context.

??????????????????????????? // 3.2.4 初始化ApplicationContext 内部的 MessageSource

??????????????? initMessageSource();

?

??????????????? // Initialize event multicaster for this context.

????????????????????????????// 3.2.5 初始化ApplicationContext 内部的 applicationEventMulticaster

??????????????? initApplicationEventMulticaster();

?

??????????????? // Initialize other special beans in specific contextsubclasses.

??????????????? onRefresh();

?

??????????????? // Check for listener beans and register them.

??????????????????????????? // 3.2.6 注册 ApplicationListeners 在配置文件cotext 中查找ApplcationListeners

?????????????????????????? // 并注册他们。

??????????????? registerListeners();

?

??????????????? // Instantiate all remaining (non-lazy-init) singletons.

??????????????????????????? // 3.2.7 初始化配置文件 context 中的所有的singleton 并且lazy-init="false"的bean

??????????????????????????? // 如果scope 不是singleton, bean将不会初始化

??????????????? finishBeanFactoryInitialization(beanFactory);

?

??????????????? // Last step: publish corresponding event.

??????????????????????????? // 3.2.8 初始化 lifecycle processor,调用LifecycleProcessor 的onRefresh() 方法

??????????????????????????? // publish ContextRefreshedEvent;

??????????????? finishRefresh();

??????????? }

?

??????????? catch (BeansException ex) {

??????????????? // Destroy already created singletons to avoid danglingresources.

??????????????? destroyBeans();

?

??????????????? // Reset 'active' flag.

??????????????? cancelRefresh(ex);

?

??????????????? // Propagate exception to caller.

??????????????? throw ex;

??????? ??? }

??????? }

??? }

?

3.3 然后接下来流程将调用BeanFactory 创建Bean 的方法.

读书人网 >软件架构设计

热点推荐