在平时的工作中,我们的很多项目都是利用Spring进行搭建的。最近有空,基于源码好好分析一下,Bean在Spring中的生命周期

这里我们先写一个简单的小例子

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="hello" class="com.hardy.pojo.Hello">
        <property name="str" value="Hello Spring"/>
    </bean>
</beans>
public class MyTest {
    public static void main(String[] args) {
        // 获取Spring 的上下文对象,即获取Spring容器
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        // 我们的对象都在Spring中管理。我们要使用,直接从中取出
        Hello hello = context.getBean("hello", Hello.class);
        System.out.println(hello.toString());
    }
}

这里我们使用xml文件注入的方式进行分析。自动注入和使用xml文件的方式类似。对于一般的singleton类型的bean来说,在获取到ApplicationContext的时候(ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml")),bean的初始化就已经完成了。

  1. bean的创建
    [Spring] Spring 中bean的生命周期-小白菜博客
    这里有一个非常重要的方法org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBeanInstance,这个方法主要是来创建bean的对象。注意:此时bean的属性都还没有填充,所以bean的初始化还没有完成
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
		...
		// 通过bean Name获取Class对象
		Class<?> beanClass = resolveBeanClass(mbd, beanName);
		...
		// 通过Class获取 java.lang.reflect.Constructor. 知道反射应该知道,这个就是构造函数对象。可以通过这个构造对象了
		Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
		...
	}
  1. bean属性的注入
    [Spring] Spring 中bean的生命周期-小白菜博客
    这里同样有一个非常重要的方法:org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#populateBean。通过函数名我们几乎就可以判断是进行属性填充的。
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
		// 设置属性值
		applyPropertyValues(beanName, mbd, bw, pvs);
	}

protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
		// 遍历属性值
		for (PropertyValue pv : original) {
			if (pv.isConverted()) {
				deepCopy.add(pv);
			}
			else {
				String propertyName = pv.getName(); // 属性名
				Object originalValue = pv.getValue(); // 属性值
			}
		}
		// 设置属性值
		bw.setPropertyValues(new MutablePropertyValues(deepCopy));

	}

明天再写