Spring Bean 生命周期

涉及到的一些测试demo地址: https://github.com/KENTLINC/framework-demo/tree/main/bean-life-test

继续开局一张图,内容全靠看源码,下图可以看作是看作是spring创建bean的一个流程

在正式开始查看源码之前,先对BeanDefinition有个初步的了解, bean的生成都是依赖于beandefinition的,如果对beanDefinition不太了解,可以看着,当然如果研读一下源码是最好的,下面再扔一张图

好了下面继续从AbstractApplicationContext.refresh开始

finishBeanFactoryInitialization开始进入最终会走到AbstractAutowireCapableBeanFactory.createBean方法,我们从这个方法进行解析

createBean

bean 实例化前置处理

@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
			throws BeanCreationException {

	.....省略
	try {
	// 实例化前操作 , 如果返回的bean 对象不为null, 那么将直接执行,不再执行后续操作
		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);
	}

	try {
          // 创建bean
	        Object beanInstance = doCreateBean(beanName, mbdToUse, args);
		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);
	}
}

resolveBeforeInstantiation

@Nullable
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) {
                // 执行实例化前置处理器
                bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
                if (bean != null) {
                    bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
                }
            }
        }
        mbd.beforeInstantiationResolved = (bean != null);
    }
    return bean;
}

applyBeanPostProcessorsBeforeInstantiation

@Nullable
protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {
    for (BeanPostProcessor bp : getBeanPostProcessors()) {
        // 如果处理器类型是InstantiationAwareBeanPostProcessor类型,那么执行前置实例化前方法
        if (bp instanceof InstantiationAwareBeanPostProcessor) {
            InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
            Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
            if (result != null) {
                return result;
            }
        }
    }
    return null;
}

举例

@Component
public class 
    
    BeforeInstantiationBeanPostProcess implements InstantiationAwareBeanPostProcessor {
    @Override
    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
        System.out.println("postProcessBeforeInstantiation()");
        if (beanClass == Student.class) {
            Student car = new Student();
            car.setName("Lin");
            return car;
        }
        return null;
    }
}

// 执行
Object student = ctx.getBean("student");
System.out.println(student);



// beans-config.xml
<bean id="student"
      class="com.lin.demo.test.Student">
    <property name="name">
        <value>lin</value>
    </property>
</bean>
<bean id="student1"
      class="com.lin.demo.test.StudentSecond">
    <property name="name">
        <value>lin</value>
    </property>
</bean>
<bean id="beforeInstantiationBeanPostProcess" class="com.lin.demo.test.BeforeInstantiationBeanPostProcess">
</bean>

实现了InstantiationAwareBeanPostProcessor

未实现InstantiationAwareBeanPostProcessor

doCreateBean

protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
    throws BeanCreationException {

    ... 省略
        if (instanceWrapper == null) {
            // 创建一个实例对象
            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 {
                // 利用后置处理器合并BeanDefinition
                applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
            }
            catch (Throwable ex) {
                throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                                "Post-processing of merged bean definition failed", ex);
            }
            mbd.postProcessed = true;
        }
    }

    // 这里是解决循环引用的问题, 提前暴露了引用
    boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
                                      isSingletonCurrentlyInCreation(beanName));
    if (earlySingletonExposure) {
        if (logger.isTraceEnabled()) {
            logger.trace("Eagerly caching bean '" + beanName +
                         "' to allow for resolving potential circular references");
        }
        addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
    }

    Object exposedObject = bean;
    try {
        // 注入bean中的属性和方法
        populateBean(beanName, mbd, instanceWrapper);
        // 初始化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);
        }
    }

    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<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
                for (String dependentBean : dependentBeans) {
                    if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
                        actualDependentBeans.add(dependentBean);
                    }
                }
                if (!actualDependentBeans.isEmpty()) {
                    ....
                }
            }
        }
        .....
    }

bean 实例化createBeanInstance

执行bean 实例化前处理BeanPostProcessor#applyBeanPostProcessorsBeforeInstantiation,

protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
	。。。 省略

    // 选择构造函数进行装配
    Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
    if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
        mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
        return autowireConstructor(beanName, mbd, ctors, args);
    }

    // Preferred constructors for default construction?
    ctors = mbd.getPreferredConstructors();
    if (ctors != null) {
        return autowireConstructor(beanName, mbd, ctors, null);
    }

    // No special handling: simply use no-arg constructor.
    return instantiateBean(beanName, mbd);
}

AbstractAutowireCapableBeanFactory#determineConstructorsFromBeanPostProcessors

这也是spring提供给我们 的一个扩展点,然后自己判断 选择哪个构造器,比如可以实现 AutowiredAnnotationBeanPostProcessor的方式

@Nullable
protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(@Nullable Class<?> beanClass, String beanName)
    throws BeansException {

    if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) {
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
                SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
                Constructor<?>[] ctors = ibp.determineCandidateConstructors(beanClass, beanName);
                if (ctors != null) {
                    return ctors;
                }
            }
        }
    }
    return null;
}

举例

@Component
public class MyInstantiationBeanPostProcess extends AutowiredAnnotationBeanPostProcessor {
    @Override
    public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, String beanName) throws BeanCreationException {
        System.out.println(beanClass);
        System.out.println("determineCandidateConstructors()");
        Constructor<?>[] declaredConstructors = beanClass.getDeclaredConstructors();
		// 这里只返回被 @MyAutowired 注释标记的的构造函数
        Constructor[] constructors = Arrays.stream(declaredConstructors).
                filter(constructor -> constructor.isAnnotationPresent(MyAutowired.class)).toArray(Constructor[]::new);
        return constructors.length != 0 ? constructors : null;
    }
}


public class Student {
    private String name;
    private Integer age;


    public Student() {
        System.out.println("执行无参数构造函数");
    }
	
    @MyAutowired
    public Student(String name, Integer age) {
        this.name = "lin";
        this.age = 123;
        System.out.println("执行所有参数构造函数");
    }

// 执行
Object student = ctx.getBean("student");
System.out.println(student);

实现了AutowiredAnnotationBeanPostProcessor

因为指定了构造函数,所以当获取bean的时候,没有无参的构造函数直接报错

未实现 AutowiredAnnotationBeanPostProcessor

未实现的时候,有无参构造函数所以能够直接执行

合并后的BeanDefinition处理

applyMergedBeanDefinitionPostProcessors,spring会调用所有MergedBeanDefinitionPostProcessorpostProcessMergedBeanDefinition方法进行一些处理, 比如AutowiredAnnotationBeanPostProcessor类 的方法中会对 @Autowired、@Value 标注的方法、字段进行解析生成一个InjectionMetadata对象进行缓存,另外CommonAnnotationBeanPostProcessor@Resource 标注的字段、@Resource 标注的方法、 @PostConstruct 标注的字段、 @PreDestroy标注的方法进行解析缓存

protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
    for (BeanPostProcessor bp : getBeanPostProcessors()) {
        if (bp instanceof MergedBeanDefinitionPostProcessor) {
            MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
            bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
        }
    }
}

bean 属性装配populateBean

protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
    。。。 省略  
    // 实例化后阶段
    if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof InstantiationAwareBeanPostProcessor) {
                InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
                    return;
                }
            }
        }
    }

    PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);

    /**
		 * 自动注入模式
		 * AUTOWIRE_BY_NAME:根据名称注入
		 * AUTOWIRE_BY_TYPE:根据类型注入
		 * 一般情况 resolvedAutowireMode == AUTOWIRE_NO
		 */
    int resolvedAutowireMode = mbd.getResolvedAutowireMode();
    if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
        MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
        // Add property values based on autowire by name if applicable.
        if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
            autowireByName(beanName, mbd, bw, newPvs);
        }
        // Add property values based on autowire by type if applicable.
        if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
            autowireByType(beanName, mbd, bw, newPvs);
        }
        pvs = newPvs;
    }

    boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
    boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);

    PropertyDescriptor[] filteredPds = null;
    /**
	 * 如果存在 InstantiationAwareBeanPostProcessor
	 * 则执行所有 InstantiationAwareBeanPostProcessor#postProcessProperties
	 * 辅助完成属性填充,诸如基于 @Autowired 等注解的属性注入就发生在此处
	*/
    if (hasInstAwareBpps) {
        if (pvs == null) {
            pvs = mbd.getPropertyValues();
        }
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof InstantiationAwareBeanPostProcessor) {
                InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
                if (pvsToUse == null) {
                    if (filteredPds == null) {
                        filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
                    }
                    pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
                    if (pvsToUse == null) {
                        return;
                    }
                }
                pvs = pvsToUse;
            }
        }
    }
    // 依赖校验
    if (needsDepCheck) {
        if (filteredPds == null) {
            filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
        }
        checkDependencies(beanName, mbd, filteredPds, pvs);
    }
    // 属性绑定
    if (pvs != null) {
        applyPropertyValues(beanName, mbd, bw, pvs);
    }
}

Bean 实例化后置处理

InstantiationAwareBeanPostProcessor#postProcessMergedBeanDefinition, 按照下述代码,可以看出,默认是返回true,如果返回false,那么将跳过后续行为

default boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
    return true;
}

示例

@Component
public class AfterInstantiationBeanPostProcess implements InstantiationAwareBeanPostProcessor {
    @Override
    public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
        if ("student1".endsWith(beanName)) {
            return false;
        }
        return true;
    }
}


ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans-config.xml");
Object student = context.getBean("student");
Object student1 = context.getBean("student1");
System.out.println(student);
System.out.println(student1);

// beans-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
        "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
    <bean id="student"
          class="com.lin.demo.test.Student">
        <property name="name">
            <value>lin</value>
        </property>
    </bean>
    <bean id="student1"
          class="com.lin.demo.test.StudentSecond">
        <property name="name">
            <value>lin</value>
        </property>
    </bean>
    <bean id="afterInstantiationBeanPostProcess" class="com.lin.demo.test.AfterInstantiationBeanPostProcess">
    </bean>
</beans>

未实现postProcessAfterInstantiation

实现postProcessAfterInstantiation

重写了这个方法,后续的属性 装配 将不会执行

#### 属性装配postProcessProperties

```java
// PropertyValues 中保存了bean实例对象中所有属性值的设置

@Nullable
default PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName)
    throws BeansException {

    return null;
}

有多个类实现了InstantiationAwareBeanPostProcessor,并且重写了postProcessProperties方法,如下图所示,比如常用的

AutowiredAnnotationBeanPostProcessor在这个方法中对@Autowired、@Value标注的字段、方法注入值

CommonAnnotationBeanPostProcessor在这个方法中对@Resource标注的字段和方法注入值

示例

public class ProcessPropertiesBeanPostProcess implements InstantiationAwareBeanPostProcessor {
    @Override
    public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
        if ("student".equals(beanName)) {
            if (pvs instanceof MutablePropertyValues) {
                MutablePropertyValues mpvs = (MutablePropertyValues) pvs;
                //将姓名设置为:postProcessPropertiesTest
                mpvs.add("name", "postProcessPropertiesTest");
                //将年龄属性的值修改为18
                mpvs.add("age", 18);
            }
        }
        return pvs;
    }
}

// 执行
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans-config.xml");
Object student = context.getBean("student");
Object student1 = context.getBean("student1");
System.out.println(student);
System.out.println(student1);

// beans-config
<bean id="student"
      class="com.lin.demo.test.Student">
    <property name="name">
        <value>lin</value>
    </property>
</bean>
<bean id="student1"
      class="com.lin.demo.test.StudentSecond">
    <property name="name">
        <value>lin</value>
    </property>
</bean>
<bean id="processPropertiesBeanPostProcess" class="com.lin.demo.test.ProcessPropertiesBeanPostProcess">
</bean>

实现了ProcessPropertiesBeanPostProcess#postProcessProperties

未实现ProcessPropertiesBeanPostProcess#postProcessProperties

在上述流程完成以后,依赖校验也完成,执行applyPropertyValues方法,循环处理PropertyValues中的属性信息, 荣国反射调用set方法将属性的值设置到bean中

applyPropertyValues

protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
		if (pvs.isEmpty()) {
			return;
		}

		if (System.getSecurityManager() != null && bw instanceof BeanWrapperImpl) {
			((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
		}

		MutablePropertyValues mpvs = null;
		List<PropertyValue> original;

		if (pvs instanceof MutablePropertyValues) {
			mpvs = (MutablePropertyValues) pvs;
			if (mpvs.isConverted()) {
				// Shortcut: use the pre-converted values as-is.
				try {
					bw.setPropertyValues(mpvs);
					return;
				}
				catch (BeansException ex) {
					throw new BeanCreationException(
							mbd.getResourceDescription(), beanName, "Error setting property values", ex);
				}
			}
			original = mpvs.getPropertyValueList();
		}
		else {
			original = Arrays.asList(pvs.getPropertyValues());
		}

		TypeConverter converter = getCustomTypeConverter();
		if (converter == null) {
			converter = bw;
		}
		BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);

		// Create a deep copy, resolving any references for values.
		List<PropertyValue> deepCopy = new ArrayList<>(original.size());
		boolean resolveNecessary = false;
		for (PropertyValue pv : original) {
			if (pv.isConverted()) {
				deepCopy.add(pv);
			}
			else {
				String propertyName = pv.getName();
				Object originalValue = pv.getValue();
				if (originalValue == AutowiredPropertyMarker.INSTANCE) {
					Method writeMethod = bw.getPropertyDescriptor(propertyName).getWriteMethod();
					if (writeMethod == null) {
						throw new IllegalArgumentException("Autowire marker for property without write method: " + pv);
					}
					originalValue = new DependencyDescriptor(new MethodParameter(writeMethod, 0), true);
				}
				Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
				Object convertedValue = resolvedValue;
				boolean convertible = bw.isWritableProperty(propertyName) &&
						!PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
				if (convertible) {
					convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter);
				}
				// Possibly store converted value in merged bean definition,
				// in order to avoid re-conversion for every created bean instance.
				if (resolvedValue == originalValue) {
					if (convertible) {
						pv.setConvertedValue(convertedValue);
					}
					deepCopy.add(pv);
				}
				else if (convertible && originalValue instanceof TypedStringValue &&
						!((TypedStringValue) originalValue).isDynamic() &&
						!(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) {
					pv.setConvertedValue(convertedValue);
					deepCopy.add(pv);
				}
				else {
					resolveNecessary = true;
					deepCopy.add(new PropertyValue(pv, convertedValue));
				}
			}
		}
		if (mpvs != null && !resolveNecessary) {
			mpvs.setConverted();
		}

		// Set our (possibly massaged) deep copy.
		try {
			bw.setPropertyValues(new MutablePropertyValues(deepCopy));
		}
		catch (BeansException ex) {
			throw new BeanCreationException(
					mbd.getResourceDescription(), beanName, "Error setting property values", ex);
		}
	}

bean初始化 initializeBean

在初始化阶段有分为几个部分

  1. Bean Aware 接口的回调
  2. Bean 初始化前操作
  3. Bean 初始化操作
  4. Bean 初始化后操作
protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
		if (System.getSecurityManager() != null) {
			AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
                // 执行aware 接口
				invokeAwareMethods(beanName, bean);
				return null;
			}, getAccessControlContext());
		}
		else {
			invokeAwareMethods(beanName, bean);
		}

		Object wrappedBean = bean;
		if (mbd == null || !mbd.isSynthetic()) {
            // Bean 初始化前操作
			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()) {
            // Bean 初始化后操作
			wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
		}

		return wrappedBean;
	}

执行Aware 接口回调invokeAwareMethods

如果bean 是Aware的实现类,会设置一些信息到bean中

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

示例

public class MyAwareBean implements BeanNameAware, BeanClassLoaderAware, BeanFactoryAware {
    @Override
    public void setBeanClassLoader(ClassLoader classLoader) {
        System.out.println("setBeanClassLoader");
    }

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

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

// 执行
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans-config.xml");
Object student = context.getBean("student");
Object student1 = context.getBean("student1");
System.out.println(student);
System.out.println(student1);

// beans-config.xml
<bean id="student"
      class="com.lin.demo.test.Student">
    <property name="name">
        <value>lin</value>
    </property>
</bean>
<bean id="student1"
      class="com.lin.demo.test.StudentSecond">
    <property name="name">
        <value>lin</value>
    </property>
</bean>
<bean id="myAwareBean" class="com.lin.demo.test.MyAwareBean">
</bean>

执行结果

bean 初始化前操作

@Override
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
    throws BeansException {

    Object result = existingBean;
    for (BeanPostProcessor processor : getBeanPostProcessors()) {
        Object current = processor.postProcessBeforeInitialization(result, beanName);
        if (current == null) {
            return result;
        }
        result = current;
    }
    return result;
}

在这个方法中执行postProcessBeforeInitialization方法, 这里有个比较重要的类ApplicationContextAwareProcessor, 能够将指定的对象注入到bean中,比如ApplicationContext对象,这里涉及到了6个Aware对象,EnvironmentAwareEmbeddedValueResolverAwareResourceLoaderAwareApplicationEventPublisherAwareMessageSourceAwareApplicationContextAware

@Override
@Nullable
public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
    AccessControlContext acc = null;

    if (System.getSecurityManager() != null &&
        (bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
         bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
         bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)) {
        acc = this.applicationContext.getBeanFactory().getAccessControlContext();
    }

    if (acc != null) {
        AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
            invokeAwareInterfaces(bean);
            return null;
        }, acc);
    }
    else {
        invokeAwareInterfaces(bean);
    }

    return bean;
}

private void invokeAwareInterfaces(Object bean) {
    if (bean instanceof Aware) {  
        if (bean instanceof EnvironmentAware) {

            ((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
        }
        if (bean instanceof EmbeddedValueResolverAware) {
            ((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);
        }
        if (bean instanceof ResourceLoaderAware) {
            ((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
        }
        if (bean instanceof ApplicationEventPublisherAware) {
            ((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
        }
        if (bean instanceof MessageSourceAware) {
            ((MessageSourceAware) bean).setMessageSource(this.applicationContext);
        }

        //我们实现ApplicationContextAware对象只需要提供setter就能得到applicationContext对象
        if (bean instanceof ApplicationContextAware) {
            if (!bean.getClass().getSimpleName().equals("IndexDao"))
                ((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
        }
    }

示例

public class MyApplicationContextAware implements ApplicationContextAware {
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        System.out.println("applicationContext");
        System.out.println(applicationContext);
    }
}

// 执行
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans-config.xml");


// beans-config.xml
 <bean id="myApplicationContextAware" class="com.lin.demo.test.MyApplicationContextAware"/>

结果

另外如果实现了@PostConstruct注解, 也会在·CommonAnnotationBeanPostProcessor#postProcessBeforeInitialization中进行调用

@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    LifecycleMetadata metadata = findLifecycleMetadata(bean.getClass());
    try {
        metadata.invokeInitMethods(bean, beanName);
    }
    catch (InvocationTargetException ex) {
        throw new BeanCreationException(beanName, "Invocation of init method failed", ex.getTargetException());
    }
    catch (Throwable ex) {
        throw new BeanCreationException(beanName, "Failed to invoke init method", ex);
    }
    return bean;
}

public void invokeInitMethods(Object target, String beanName) throws Throwable {
    Collection<LifecycleElement> checkedInitMethods = this.checkedInitMethods;
    Collection<LifecycleElement> initMethodsToIterate =
        (checkedInitMethods != null ? checkedInitMethods : this.initMethods);
    if (!initMethodsToIterate.isEmpty()) {
        for (LifecycleElement element : initMethodsToIterate) {
            if (logger.isTraceEnabled()) {
                logger.trace("Invoking init method on bean '" + beanName + "': " + element.getMethod());
            }
            element.invoke(target);
        }
    }
}

示例

public class Student {
    private String name;
    private Integer age;

    @PostConstruct
    public void init() {
        System.out.println("init");
        this.name = "PostConstruct";
    }

    public Student() {
        System.out.println("执行无参数构造函数");
    }
    
// 执行
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans-config.xml");
Object student = context.getBean("student");
System.out.println(student);


// beans-config.xml
 <context:annotation-config/>
<bean id="student"
      class="com.lin.demo.test.Student">
    <property name="name">
        <value>lin</value>
    </property>
</bean>  

结果

Bean初始化

在bean 初始化分为两个步骤

  1. 如果bean 是实现了InitializingBean接口, 那么会调用afterPropertiesSet方法
  2. 如果bean指定了初始化方法,那么调用指定初始化方法
protected void invokeInitMethods(String beanName, Object bean, @Nullable RootBeanDefinition mbd)
			throws Throwable {

		boolean isInitializingBean = (bean instanceof InitializingBean);
		if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
			if (logger.isTraceEnabled()) {
				logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
			}
			if (System.getSecurityManager() != null) {
				try {
					AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
						((InitializingBean) bean).afterPropertiesSet();
						return null;
					}, getAccessControlContext());
				}
				catch (PrivilegedActionException pae) {
					throw pae.getException();
				}
			}
			else {
                // 如果实现了`InitializingBean`接口, 那么会调用`afterPropertiesSet`方法
				((InitializingBean) bean).afterPropertiesSet();
			}
		}

		if (mbd != null && bean.getClass() != NullBean.class) {
			String initMethodName = mbd.getInitMethodName();
			if (StringUtils.hasLength(initMethodName) &&
					!(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
					!mbd.isExternallyManagedInitMethod(initMethodName)) {
                // 通过反射的方式调用自定义的init 方法
				invokeCustomInitMethod(beanName, bean, mbd);
			}
		}
	}

invokeCustomInitMethod

	protected void invokeCustomInitMethod(String beanName, Object bean, RootBeanDefinition mbd)
			throws Throwable {

		String initMethodName = mbd.getInitMethodName();
		Assert.state(initMethodName != null, "No init method set");
        // 获取声明的init方法
		Method initMethod = (mbd.isNonPublicAccessAllowed() ?
				BeanUtils.findMethod(bean.getClass(), initMethodName) :
				ClassUtils.getMethodIfAvailable(bean.getClass(), initMethodName));

		if (initMethod == null) {
			if (mbd.isEnforceInitMethod()) {
				throw new BeanDefinitionValidationException("Could not find an init method named '" +
						initMethodName + "' on bean with name '" + beanName + "'");
			}
			else {
				if (logger.isTraceEnabled()) {
					logger.trace("No default init method named '" + initMethodName +
							"' found on bean with name '" + beanName + "'");
				}
				// Ignore non-existent default lifecycle methods.
				return;
			}
		}

		if (logger.isTraceEnabled()) {
			logger.trace("Invoking init method  '" + initMethodName + "' on bean with name '" + beanName + "'");
		}
		Method methodToInvoke = ClassUtils.getInterfaceMethodIfPossible(initMethod);

		if (System.getSecurityManager() != null) {
			AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
				ReflectionUtils.makeAccessible(methodToInvoke);
				return null;
			});
			try {
				AccessController.doPrivileged((PrivilegedExceptionAction<Object>)
						() -> methodToInvoke.invoke(bean), getAccessControlContext());
			}
			catch (PrivilegedActionException pae) {
				InvocationTargetException ex = (InvocationTargetException) pae.getException();
				throw ex.getTargetException();
			}
		}
		else {
			try {
                // 利用放射的方式调用init方法
				ReflectionUtils.makeAccessible(methodToInvoke);
				methodToInvoke.invoke(bean);
			}
			catch (InvocationTargetException ex) {
				throw ex.getTargetException();
			}
		}
	}

示例

public class StudentInitializingBean implements InitializingBean {
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("afterPropertiesSet");
    }

    public void init() {
        System.out.println("StudentInitializingBean.init");
    }
}

// 执行
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans-config.xml");

// beans-config.xml
<bean id="studentInitializingBean" class="com.lin.demo.test.StudentInitializingBean" init-method="init"/>

执行结果

Bean初始化后置处理

@Override
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
    throws BeansException {

    Object result = existingBean;
    for (BeanPostProcessor processor : getBeanPostProcessors()) {
        Object current = processor.postProcessAfterInitialization(result, beanName);
        if (current == null) {
            return result;
        }
        result = current;
    }
    return result;
}

在后置处理器中如果返回null,那么将会终端后续操作, 其实这个后置处理器干了挺多事情,如果在创建bean的时候没有发现循环依赖,并且bean 是需要被代理的对象,那么被代理的行为就是在初始化的后置处理中进行,会调用AspectJAwareAdvisorAutoProxyCreator#postProcessAfterInitialization,方法实际实在其父类AbstractAutoProxyCreator中,在wrapIfNecessary进行代理对象的创建,这里暂时不进行展开,后续补充

public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
    if (bean != null) {
        Object cacheKey = this.getCacheKey(bean.getClass(), beanName);
        if (this.earlyProxyReferences.remove(cacheKey) != bean) {
            // 生成代理对象
            return this.wrapIfNecessary(bean, beanName, cacheKey);
        }
    }

    return bean;
}

示例

public class MyAfterInitializationBeanPostProcess implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("MyAfterInitializationBeanPostProcess.postProcessAfterInitialization");
        return bean;
    }
}

// 执行
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans-config.xml");
Object student = context.getBean("student");
System.out.println(student);

// beans-config.xml
<bean id="student"
      class="com.lin.demo.test.Student">
    <property name="name">
        <value>lin</value>
    </property>
</bean>
<bean id="myAfterInitializationBeanPostProcess"  class="com.lin.demo.test.MyAfterInitializationBeanPostProcess"/>

结果

所有单例执行完成之后

在单例加载创建完成之后会进行一些设置, 比如事件监听的注册EventListenerMethodProcessor

调用路径AbstractApplicationContext#refresh -> AbstractApplicationContext#finishBeanFactoryInitialization -> DefaultListableBeanFactory#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);

    // Trigger initialization of all non-lazy singleton beans...
    for (String beanName : beanNames) {
        RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
        if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
            if (isFactoryBean(beanName)) {
                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);
            }
        }
    }

    // Trigger post-initialization callback for all applicable beans...
    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();
            }
        }
    }
}

示例

public class MyAfterSingletonsInstantiated implements SmartInitializingSingleton {
    @Override
    public void afterSingletonsInstantiated() {
        System.out.println("最后执行 MyAfterSingletonsInstantiated.afterSingletonsInstantiated");
    }
}

// 执行
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans-config.xml");

// beans-config.xml
<bean id="student"
      class="com.lin.demo.test.Student">
    <property name="name">
        <value>lin</value>
    </property>
</bean>
<bean id="student1"
      class="com.lin.demo.test.StudentSecond">
    <property name="name">
        <value>lin</value>
    </property>
</bean>
<bean id="myAfterSingletonsInstantiated"  class="com.lin.demo.test.MyAfterSingletonsInstantiated"/>

结果

上述就是spring bean 的创建的源码阅读的一些流程,其中还有bean 的销毁 和 其中涉及到一些比如说解决循环引用问题, 比如说事件监听的行为,留到其他文章进行描述

posted @   苜蓿椒盐  阅读(38)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示