1.前言
bean的生命周期,无非是bean的创建--->初始化---->销毁这三步 ,为了给这个概念具象化,下面给出一个例子说明。比如:现在有个类A,那么上述三个步骤分别是:
- 创建,即:调用A的构造方法;
- 初始化,即:调用A的set方法,进行赋值操作;
- 销毁,即:Java对象的销毁,一般情况下程序员是不用手动去操作的,因为Java有GC机制,参考《深入理解Java虚拟机》。
上述三个步骤在Spring中的实现,比较复杂,不过步骤还是上述三步。
2.Demo介绍
Bike.java
package cn.enjoy.cap7;
public class Bike {
//无参构造器
public Bike(){
System.out.println("call constructor");
}
//初始化方法
public void init(){
System.out.println("bean....init");
}
//bean的销毁方法
public void destroy(){
System.out.println("bean....destroy");
}
}
配置类:
package cn.enjoy.cap7;
import cn.enjoy.cap1.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class Cap7MainConfigOfLifeCycle {
@Bean
public Person person(){
return new Person("xugui",12);
}
/**
* 引入了自定义的init和destroy方法
*
* @return
*/
@Bean(initMethod = "init",destroyMethod = "destroy")
public Bike bike(){
return new Bike();
}
}
测试类:
import cn.enjoy.cap7.Cap7MainConfigOfLifeCycle;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Cap7Test {
@Test
public void test(){
AnnotationConfigApplicationContext app = new AnnotationConfigApplicationContext(Cap7MainConfigOfLifeCycle.class);
System.out.println("IOC容器创建完成");
app.close();
}
}
3. bean对象的创建和赋值
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// Initialize conversion service for this context.
//初始化上下文的转接服务,逻辑:判断beanFactory中是否存在conversion service的bean,类型是否匹配,满足条件则获取
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.
//如果没有bean后处理器,注册一个默认的嵌入式值解析器
//(例如PropertyPlaceholderConfigurer bean)
//此时,主要用于解析注释属性值
if (!beanFactory.hasEmbeddedValueResolver()) { //true
beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
}
// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
//尽早初始化LoadTimeWeaverAware bean,以便尽早注册它们的转换器
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {//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.
//允许缓存所有bean definition元数据,而不期望进一步的更改。
beanFactory.freezeConfiguration();
// Instantiate all remaining (non-lazy-init) singletons.
beanFactory.preInstantiateSingletons(); //详见3.1
}
3.1 beanFactory.preInstantiateSingletons()方法详解
public void preInstantiateSingletons() throws BeansException {
if (logger.isTraceEnabled()) { //日志追踪,判断该日志有没有进行实际追踪
logger.trace("Pre-instantiating singletons in " + this);
}
// Iterate over a copy to allow for init methods which in turn register new bean definitions.
// While this may not be part of the regular factory bootstrap, it does otherwise work fine.
List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);//新建List结构,这个构造器比较特殊
//该构造器构造了一个包含所有beanName的List结构,beanDefinitionName这个List在register阶段已经赋值
// Trigger initialization of all non-lazy singleton beans...
//触发所有的非懒加载的bean的初始化
for (String beanName : beanNames) {
//会对beanNames中所有的bean名称获取其真正的实例对象
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName); //对名为beanName的bean进行包装,包装为RootBeanDefinition的形式
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) { //true
if (isFactoryBean(beanName)) { //判断beanName指定的类是否定义为FactoryBean类型,当前beanNames中是没有符合条件的,故而直接执行else代码块
Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
if (bean instanceof FactoryBean) {
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());
}
if (isEagerInit) {
getBean(beanName);
}
}
}
else {
getBean(beanName); //里面获得bean,底层调用doGetBean方法,其中该方法的分类类似之前分析register过程类似,详见3.2
}
}
}
// Trigger post-initialization callback for all applicable beans...
//为所有适用的bean触发初始化后回调
//本例中的bike bean没有进入下列代码块
for (String beanName : beanNames) {
Object singletonInstance = getSingleton(beanName);
if (singletonInstance instanceof SmartInitializingSingleton) {
SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
smartSingleton.afterSingletonsInstantiated();
return null;
}, getAccessControlContext());
}
else {
smartSingleton.afterSingletonsInstantiated();
}
}
}
}
3.2 getBean方法详解
public Object getBean(String name) throws BeansException { //与之前分析register方法里面是类似的,获得bean实例对象
return doGetBean(name, null, null, false);
}
protected <T> T doGetBean(
String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)//name:"bike" null false
throws BeansException {
String beanName = transformedBeanName(name);//获取beanName,如果有前缀 去掉前缀
Object bean;//定义bean
// Eagerly check singleton cache for manually registered singletons.
Object sharedInstance = getSingleton(beanName);//给定beanName获得单例对象,null
if (sharedInstance != null && args == null) {
if (logger.isTraceEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
}
}
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
else {
// Fail if we're already creating this bean instance:
// We're assumably within a circular reference.
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
// Check if bean definition exists in this factory.
BeanFactory parentBeanFactory = getParentBeanFactory();//获取BeanFactory对象,为null
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// Not found -> check parent.
String nameToLookup = originalBeanName(name);
if (parentBeanFactory instanceof AbstractBeanFactory) {
return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
nameToLookup, requiredType, args, typeCheckOnly);
}
else if (args != null) {
// Delegation to parent with explicit args.
return (T) parentBeanFactory.getBean(nameToLookup, args);
}
else if (requiredType != null) {
// No args -> delegate to standard getBean method.
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
else {
return (T) parentBeanFactory.getBean(nameToLookup);
}
}
if (!typeCheckOnly) {//false
markBeanAsCreated(beanName);
}
try {
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); //通过beanName,获得RootBeanDefinition对象,注意在spring中一般用beanDifinition对象包装bean
checkMergedBeanDefinition(mbd, beanName, args);//通过抛出异常的方式校验RootBeanDefinition对象
// Guarantee initialization of beans that the current bean depends on.保证初始化当前bean所依赖的bean
String[] dependsOn = mbd.getDependsOn();//null,当前bean没有依赖得bean
if (dependsOn != null) { //false
for (String dep : dependsOn) {
if (isDependent(beanName, dep)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
registerDependentBean(dep, beanName);
try {
getBean(dep);
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
}
}
}
// Create bean instance.
if (mbd.isSingleton()) {//true
sharedInstance = getSingleton(beanName, () -> {
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);//如果产生异常则销毁bean,后面继续研究
throw ex;
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);//进入底层发现,本例中直接返回的是sharedInstance,所以bean的初始化在上代码中进行
}
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();
if (!StringUtils.hasLength(scopeName)) {
throw new IllegalStateException("No scope name defined for bean ´" + beanName + "'");
}
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, () -> {
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;
}
}
// Check if required type matches the type of the actual bean instance.
//false
if (requiredType != null && !requiredType.isInstance(bean)) {//false
try {
T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
if (convertedBean == null) {
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
return convertedBean;
}
catch (TypeMismatchException ex) {
if (logger.isTraceEnabled()) {
logger.trace("Failed to convert bean '" + name + "' to required type '" +
ClassUtils.getQualifiedName(requiredType) + "'", ex);
}
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
return (T) bean;//返回Bike@xxx
}
3.3 getSingleton方法详解
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "Bean name must not be null");
synchronized (this.singletonObjects) {
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
if (this.singletonsCurrentlyInDestruction) {
throw new BeanCreationNotAllowedException(beanName,
"Singleton bean creation not allowed while singletons of this factory are in destruction " +
"(Do not request a bean from a BeanFactory in a destroy method implementation!)");
}
if (logger.isDebugEnabled()) {
logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
}
beforeSingletonCreation(beanName);//底层就是异常处理,可以看成一种检查机制
boolean newSingleton = false;
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<>();
}
try {
//创建单例的bean,详见3.4
singletonObject = singletonFactory.getObject();
newSingleton = true; //标志位
}
catch (IllegalStateException ex) {
// Has the singleton object implicitly appeared in the meantime ->
// if yes, proceed with it since the exception indicates that state.
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
throw ex;
}
}
catch (BeanCreationException ex) {
if (recordSuppressedExceptions) {
for (Exception suppressedException : this.suppressedExceptions) {
ex.addRelatedCause(suppressedException);
}
}
throw ex;
}
finally {
if (recordSuppressedExceptions) {
this.suppressedExceptions = null;
}
afterSingletonCreation(beanName);//底层就是异常处理,可以看成一种检查机制
}
if (newSingleton) {
addSingleton(beanName, singletonObject);//做缓存,放在singletonObject中
}
}
return singletonObject; //返回@Bike
}
}
3.4 public Object getSingleton(String name, ObjectFactory<?> singletonFactory) 方法详解
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "Bean name must not be null");//非空检查
synchronized (this.singletonObjects) {///** Cache of singleton objects: bean name to bean instance. */
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {//true
if (this.singletonsCurrentlyInDestruction) {//判断当前bean是否正在被销毁,false
throw new BeanCreationNotAllowedException(beanName,
"Singleton bean creation not allowed while singletons of this factory are in destruction " +
"(Do not request a bean from a BeanFactory in a destroy method implementation!)");
}
if (logger.isDebugEnabled()) {//当前是否启用了调试日志记录,false,其实可忽略
logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
}
beforeSingletonCreation(beanName);//底层就是异常处理,可以看成一种检查机制
boolean newSingleton = false;
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);//true
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<>();//初始化suppressedExceptions
}
try {
//*************创建单例的bean,详见3.4******************
singletonObject = singletonFactory.getObject();
newSingleton = true; //标志位
}
catch (IllegalStateException ex) {//异常处理
// Has the singleton object implicitly appeared in the meantime ->
// if yes, proceed with it since the exception indicates that state.
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
throw ex;
}
}
catch (BeanCreationException ex) {
if (recordSuppressedExceptions) {
for (Exception suppressedException : this.suppressedExceptions) {
ex.addRelatedCause(suppressedException);
}
}
throw ex;
}
finally {
if (recordSuppressedExceptions) {
this.suppressedExceptions = null;//将suppressedExceptions无效,设置为null
}
afterSingletonCreation(beanName);//底层就是异常处理,可以看成一种检查机制
}
if (newSingleton) { //true
addSingleton(beanName, singletonObject);//做缓存,放在singletonObject中
}
}
return singletonObject; //返回@Bike
}
}
3.5 protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
if (logger.isTraceEnabled()) { //判断是否启动了日志跟踪,false
logger.trace("Creating instance of bean '" + beanName + "'");
}
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.
//确保bean类确实被解析,并以动态解析类(不可以在共享的bean信息中进行存储的)的方式克隆bean信息
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);//null,解析给定bean信息
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {//false
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 {
// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
// 给BeanPostProcessors一个返回代理而不是目标bean实例的机会
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);//null
if (bean != null) {
return bean;
}
}
catch (Throwable ex) {
throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
}
try {
//***********bean的创建和初始化方法**********
Object beanInstance = doCreateBean(beanName, mbdToUse, args);//参数:“bike”,rootBean...,null,详见3.6
if (logger.isTraceEnabled()) {//日志跟踪
logger.trace("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
// A previously detected exception with proper bean creation context already,
// or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
throw ex;
}
catch (Throwable ex) {
throw new BeanCreationException(
mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
}
}
3.6 protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)方法详解
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException { //参数:“bike”,rootBean...,null
// Instantiate the bean.初始化bean
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {//false
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
Object bean = instanceWrapper.getWrappedInstance();//通过Bean包装类获取bean对象实例
Class<?> beanType = instanceWrapper.getWrappedClass();//beanType:cn.enjoy.cap7.Bike
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;//(包可见的字段,用于缓存给定bean定义的确定类),缓存
}
// 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;
}
}
// 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));//true
if (earlySingletonExposure) {
if (logger.isTraceEnabled()) {
logger.trace("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));//添加给定的单例对象工厂来构建指定的单例对象
}
// Initialize the bean instance.
Object exposedObject = bean;
try {
populateBean(beanName, mbd, instanceWrapper);//用属性值填充给定BeanWrapper中的bean实例
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);
}
}
/*********真正的bean的初始化**********/
if (earlySingletonExposure) { //true
Object earlySingletonReference = getSingleton(beanName, false); //获取Bike@xxx
if (earlySingletonReference != null) {//true
if (exposedObject == bean) { //true
exposedObject = earlySingletonReference; //Bike@xxx
}
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
String[] dependentBeans = getDependentBeans(beanName);
Set<String> 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 " +
"'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
}
}
}
}
// Register bean as disposable.将bean注册为一次性的
try {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject; //返回Bike@xxx
}
上述过程呢,下面进行总结:
容器启动加载配置类--->refresh()--->finishBeanFactoryInitialization()--->getBean()--->doCreateBean--->beanWrapper(包装对象的创建)--->populated(属性赋值)--->inializate(初始化)--->processors(后置处理器,new出对象)