SourceCode Code java Sring

Spring Bean生命周期

Posted on 2021-03-15,5 min read

Bean的生命周期

  • 实例化
  • 属性赋值
  • 初始化
  • 销毁
//AbstractAutowireCapableBeanFactory.class
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
      throws BeanCreationException {

   // Instantiate the bean.
   BeanWrapper instanceWrapper = null;
   if (instanceWrapper == null) {
       // 实例化阶段!
      instanceWrapper = createBeanInstance(beanName, mbd, args);
   }

   // Initialize the bean instance.
   Object exposedObject = bean;
   try {
       // 属性赋值阶段!
      populateBean(beanName, mbd, instanceWrapper);
       // 初始化阶段!
      exposedObject = initializeBean(beanName, exposedObject, mbd);
   }
}

图解

SpringBean的生命周期

代码

createBean:

// AbstractAutowireCapableBeanFactory.class
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
			throws BeanCreationException {
		...

		// Prepare method overrides.
		try {
			mbdToUse.prepareMethodOverrides();
		}
		catch (BeanDefinitionValidationException ex) {
			throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
					beanName, "Validation of method overrides failed", ex);
		}

		try {
            // 调用InstantiationAwareBeanPostProcessor的postProcessBeforeInstantiation
			// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
			Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
			if (bean != null) {
				return bean;
			}
		}
		catch (Throwable ex) {

		}

		try {
            // 调用doCreateBean方法
			Object beanInstance = doCreateBean(beanName, mbdToUse, args);
			if (logger.isTraceEnabled()) {
				logger.trace("Finished creating instance of bean '" + beanName + "'");
			}
			return beanInstance;
		}
		catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {

		}
		catch (Throwable ex) {

		}
	}

doCreateBean:

// AbstractAutowireCapableBeanFactory.class
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) {
        // 初始化对象,相当于new Object
        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 {
                applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
            }
            catch (Throwable ex) {
                throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                        "Post-processing of merged bean definition failed", ex);
            }
            mbd.postProcessed = true;
        }
    }

    ...

    // Initialize the bean instance.
    Object exposedObject = bean;
    try {
        /**
         * 属性赋值:
         *  执行InstantiationAwareBeanPostProcessors的postProcessAfterInstantiation方法
         *  调用InstantiationAwareBeanPostProcessor的postProcessPropertyValues方法
         *  注入属性,具体通过:applyPropertyValues方法
         */
        populateBean(beanName, mbd, instanceWrapper);
        /**
         * 初始化Bean:
         *  调用各种Aware,具体通过:invokeAwareMethods方法
         *  调用BeanPostProcessor的postProcessBeforeInitialization方法
         *  调用Bean的init方法:通过:invokeInitMethods。在调用init方法之前如果实现了InitializingBean接口,则会调用afterPropertiesSet方法
         *  调用BeanPostProcessor的postProcessAfterInitialization方法
         */
        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);
        }
    }
    ...
}

SpringAOP自动代理

此处待补充
动态代理相关的类

  • SpringAOP的自动代理是通过BeanPostProcessor来实现的。在调用InstantiationBean的时候,会调用postProcessAfterInitialization方法,此时会调用到AbstractAdvisorAutoProxyCreator的相关方法,来实现自动代理。

测试代码

/**
 * 测试Bean
 */
@Component
public class Person implements BeanFactoryAware, BeanNameAware,
        InitializingBean, DisposableBean {
    private String filed;

    @Value("filed")
    public void setFiled(String filed) {
        System.out.println("执行Bean的属性注入");
        this.filed = filed;
    }

    public Person(){
        System.out.println("执行Bean的构造方法");
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        System.out.println("执行BeanFactoryAware的setBeanFactory");
    }

    @Override
    public void setBeanName(String name) {
        System.out.println("执行BeanNameAware的setBeanName");
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("执行Bean的销毁方法");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("执行InitializingBean的afterPropertiesSet");
    }

    @Override
    public String toString() {
        return "Person{" +
                "filed='" + filed + '\'' +
                '}';
    }
}


/**
 * 自定义处理器
 */
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("执行MyBeanPostProcessor的postProcessBeforeInitialization");
        return null;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("执行MyBeanPostProcessor的postProcessAfterInitialization");

        return null;
    }
}


/**
 * 自定义Bean实例化处理器
 */
@Component
public class MyInstantiationAwareBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter {
    @Override
    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
        System.out.println("MyInstantiationAwareBeanPostProcessor调用postProcessBeforeInstantiation");
        return super.postProcessBeforeInstantiation(beanClass, beanName);
    }

    @Override
    public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
        System.out.println("MyInstantiationAwareBeanPostProcessor调用postProcessAfterInstantiation");

        return super.postProcessAfterInstantiation(bean, beanName);
    }

    @Override
    public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
        System.out.println("MyInstantiationAwareBeanPostProcessor调用postProcessProperties");

        return super.postProcessProperties(pvs, bean, beanName);
    }
}

/**
 * 配置包扫描
 */
@ComponentScan("spring")
public class Config {
}


/**
 * 主方法
 */
public class App {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
        Person person = (Person)context.getBean("person");
        try {
            person.destroy();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

下一篇: Linux解决Idea光标不跟随→

loading...