Spring源码分析(二)bean的实例化和IOC依赖注入

前言

我们知道,IOC是Spring的核心。它来负责控制对象的生命周期和对象间的关系。
举个例子,我们如何来找对象的呢?常见的情况是,在路上要到处去看哪个MM既漂亮身材又好,符合我们的口味。就打听她们的电话号码,制造关联想办法认识她们,然后...这里省略N步,最后谈恋爱结婚。
IOC在这里就像婚介所,里面有很多适婚男女的资料,如果你有需求,直接告诉它你需要个什么样的女朋友就好了。它会给我们提供一个MM,直接谈恋爱结婚,完美!
下面就来看Spring是如何生成并管理这些对象的呢?

1、方法入口

org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons()方法是今天的主角,一切从它开始。

  public void preInstantiateSingletons() throws BeansException {
        //beanDefinitionNames就是上一节初始化完成后的所有BeanDefinition的beanName
        List<String> beanNames = new ArrayList<String>(this.beanDefinitionNames);
        for (String beanName : beanNames) {
            RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
            if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
                //getBean是主力中的主力,负责实例化Bean和IOC依赖注入
                getBean(beanName);
            }
        }
    }

2、Bean的实例化

在入口方法getBean中,首先调用了doCreateBean方法。第一步就是通过反射实例化一个Bean。

    protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) {
        // Instantiate the bean.
        BeanWrapper instanceWrapper = null;
        if (mbd.isSingleton()) {
            instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
        }
        if (instanceWrapper == null) {
            //createBeanInstance就是实例化Bean的过程,无非就是一些判断加反射,最后调用ctor.newInstance(args);
            instanceWrapper = createBeanInstance(beanName, mbd, args);
        }
    }

3、Annotation的支持

在Bean实例化完成之后,会进入一段后置处理器的代码。从代码上看,过滤实现了MergedBeanDefinitionPostProcessor接口的类,调用其postProcessMergedBeanDefinition()方法。都是谁实现了MergedBeanDefinitionPostProcessor接口呢?我们重点看三个

AutowiredAnnotationBeanPostProcessor
CommonAnnotationBeanPostProcessor
RequiredAnnotationBeanPostProcessor

记不记得在Spring源码分析(一)Spring的初始化和XML这一章节中,我们说Spring对annotation-config标签的支持,注册了一些特殊的Bean,正好就包含上面这三个。下面来看它们偷偷做了什么呢?
从方法名字来看,它们做了相同一件事,加载注解元数据。方法内部又做了相同的两件事

ReflectionUtils.doWithLocalFields(targetClass, new ReflectionUtils.FieldCallback() 
ReflectionUtils.doWithLocalMethods(targetClass, new ReflectionUtils.MethodCallback()

看方法的参数,targetClass就是Bean的Class对象。接下来就可以获取它的字段和方法,判断是否包含了相应的注解,最后转成InjectionMetadata对象,下面以一段伪代码展示处理过程。

    public static void main(String[] args) throws ClassNotFoundException {
        Class<?> clazz = Class.forName("com.viewscenes.netsupervisor.entity.User");
        Field[] fields = clazz.getFields();
        Method[] methods = clazz.getMethods();

        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            if (field.isAnnotationPresent(Autowired.class)) {
                //转换成AutowiredFieldElement对象,加入容器
            }
        }
        for (int i = 0; i < methods.length; i++) {
            Method method = methods[i];
            if (method.isAnnotationPresent(Autowired.class)) {
                //转换成AutowiredMethodElement对象,加入容器
            }
        }
        return new InjectionMetadata(clazz, elements);
    }

InjectionMetadata对象有两个重要的属性:targetClass ,injectedElements,在注解式的依赖注入的时候重点就靠它们。

    public InjectionMetadata(Class<?> targetClass, Collection<InjectedElement> elements) {
        //targetClass是Bean的Class对象
        this.targetClass = targetClass; 
        //injectedElements是一个InjectedElement对象的集合
        this.injectedElements = elements;
    }
    //member是成员本身,字段或者方法
    //pd是JDK中的内省机制对象,后面的注入属性值要用到
    protected InjectedElement(Member member, PropertyDescriptor pd) {
        this.member = member;
        this.isField = (member instanceof Field);
        this.pd = pd;
    }

说了这么多,最后再看下源码里面是什么样的,以Autowired 为例。

ReflectionUtils.doWithLocalFields(targetClass, new ReflectionUtils.FieldCallback() {
    @Override
    public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
        AnnotationAttributes ann = findAutowiredAnnotation(field);
        if (ann != null) {
            if (Modifier.isStatic(field.getModifiers())) {
                if (logger.isWarnEnabled()) {
                    logger.warn("Autowired annotation is not supported on static fields: " + field);
                }
                return;
            }
            boolean required = determineRequiredStatus(ann);
            currElements.add(new AutowiredFieldElement(field, required));
        }
    }
});

ReflectionUtils.doWithLocalMethods(targetClass, new ReflectionUtils.MethodCallback() {
    @Override
    public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
        Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
        if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
            return;
        }
        AnnotationAttributes ann = findAutowiredAnnotation(bridgedMethod);
        if (ann != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
            if (Modifier.isStatic(method.getModifiers())) {
                if (logger.isWarnEnabled()) {
                    logger.warn("Autowired annotation is not supported on static methods: " + method);
                }
                return;
            }
            if (method.getParameterTypes().length == 0) {
                if (logger.isWarnEnabled()) {
                    logger.warn("Autowired annotation should be used on methods with parameters: " + method);
                }
            }
            boolean required = determineRequiredStatus(ann);
            PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
            currElements.add(new AutowiredMethodElement(method, required, pd));
        }
    }
});

4、依赖注入

前面完成了在doCreateBean()方法Bean的实例化,接下来就是依赖注入。
Bean的依赖注入有两种方式,一种是配置文件,一种是注解式。

4.1、 注解式的注入过程

在上面第3小节,Spring已经过滤了Bean实例上包含@Autowired、@Resource等注解的Field和Method,并返回了包含Class对象、内省对象、成员的InjectionMetadata对象。还是以@Autowired为例,这次调用到AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues()
首先拿到InjectionMetadata对象,再判断里面的InjectedElement集合是否为空,也就是说判断在Bean的字段和方法上是否包含@Autowired。然后调用InjectedElement.inject()。InjectedElement有两个子类AutowiredFieldElement、AutowiredMethodElement,很显然一个是处理Field,一个是处理Method。

4.1.1 AutowiredFieldElement

如果Autowired注解在字段上,它的配置是这样。

public class User { 
    @Autowired
    Role role;
}
protected void inject(Object bean, String beanName, PropertyValues pvs) throws Throwable {
    //以User类中的@Autowired Role role为例,这里的field就是
    //public com.viewscenes.netsupervisor.entity.Role com.viewscenes.netsupervisor.entity.User.role
    Field field = (Field) this.member;
    Object value;
    DependencyDescriptor desc = new DependencyDescriptor(field, this.required);
    desc.setContainingClass(bean.getClass());
    Set<String> autowiredBeanNames = new LinkedHashSet<String>(1);
    TypeConverter typeConverter = beanFactory.getTypeConverter();
    try {
        //这里的beanName因为Bean,所以会重新进入populateBean方法,先完成Role对象的注入
        //value == com.viewscenes.netsupervisor.entity.Role@7228c85c
        value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);
    }
    catch (BeansException ex) {
        throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(field), ex);
    }
    if (value != null) {
        //设置可访问,直接赋值
        ReflectionUtils.makeAccessible(field);
        field.set(bean, value);
    }
}
4.1.2 AutowiredFieldElement

如果Autowired注解在方法上,就得这样写。

public class User {
    @Autowired
    public void setRole(Role role) {}
}

它的inject方法和上面类似,不过最后是method.invoke。感兴趣的小伙伴可以去翻翻源码。

ReflectionUtils.makeAccessible(method);
method.invoke(bean, arguments);

4.2、配置文件的注入过程

先来看一个配置文件,我们在User类中注入了id,name,age和Role的实例。

    <bean id="user" class="com.viewscenes.netsupervisor.entity.User">
        <property name="id" value="1001"></property>
        <property name="name" value="网机动车"></property>
        <property name="age" value="24"></property>
        <property name="role" ref="role"></property>
    </bean>
    <bean id="role" class="com.viewscenes.netsupervisor.entity.Role">
        <property name="id" value="1002"></property>
        <property name="name" value="中心管理员"></property>
    </bean>

Spring源码分析(一)Spring的初始化和XML这一章节的4.2 小节,bean标签的解析,我们看到在反射得到Bean的Class对象后,会设置它的property属性,也就是调用了parsePropertyElements()方法。在BeanDefinition对象里有个MutablePropertyValues属性。

MutablePropertyValues:
  //propertyValueList就是有几个property 节点
  List<PropertyValue> propertyValueList:
    PropertyValue:
      name      //对应配置文件中的name    ==id
      value     //对应配置文件中的value  ==1001 
    PropertyValue:
      name      //对应配置文件中的name    ==name
      value     //对应配置文件中的value  ==网机动车 

上图就是BeanDefinition对象里面MutablePropertyValues属性的结构。既然已经拿到了property的名称和值,注入就比较简单了。从内省对象PropertyDescriptor中拿到writeMethod对象,设置可访问,invoke即可。PropertyDescriptor有两个对象readMethodRef、writeMethodRef其实对应的就是get set方法。

public void setValue(final Object object, Object valueToApply) throws Exception {
    //pd 是内省对象PropertyDescriptor
    final Method writeMethod = this.pd.getWriteMethod());
    writeMethod.setAccessible(true);
    final Object value = valueToApply;
    //以id为例  writeMethod == public void com.viewscenes.netsupervisor.entity.User.setId(java.lang.String)
    writeMethod.invoke(getWrappedInstance(), value);
}

5、initializeBean

在Bean实例化和IOC依赖注入后,Spring留出了扩展,可以让我们对Bean做一些初始化的工作。

5.1、Aware

Aware是一个空的接口,什么也没有。不过有很多xxxAware继承自它,下面来看源码。如果有需要,我们的Bean可以实现下面的接口拿到我们想要的。

    //在实例化和IOC依赖注入完成后调用
        private void invokeAwareMethods(final String beanName, final Object bean) {
        if (bean instanceof Aware) {
            //让我们的Bean可以拿到自身在容器中的beanName
            if (bean instanceof BeanNameAware) {
                ((BeanNameAware) bean).setBeanName(beanName);
            }
            //可以拿到ClassLoader对象
            if (bean instanceof BeanClassLoaderAware) {
                ((BeanClassLoaderAware) bean).setBeanClassLoader(getBeanClassLoader());
            }
            //可以拿到BeanFactory对象
            if (bean instanceof BeanFactoryAware) {
                ((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
            }
            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);
            }
            if (bean instanceof ApplicationContextAware) {
                ((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
            }
            ......未完
        }
    }

做法如下:

public class AwareTest1 implements BeanNameAware,BeanClassLoaderAware,BeanFactoryAware{
    public void setBeanName(String name) {
        System.out.println("BeanNameAware:" + name);
    }
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        System.out.println("BeanFactoryAware:" + beanFactory);  
    }
    public void setBeanClassLoader(ClassLoader classLoader) {
        System.out.println("BeanClassLoaderAware:" + classLoader);  
    }
}
//输出结果
BeanNameAware:awareTest1
BeanClassLoaderAware:WebappClassLoader
  context: /springmvc_dubbo_producer
  delegate: false
  repositories:
    /WEB-INF/classes/
----------> Parent Classloader:
java.net.URLClassLoader@2626b418
BeanFactoryAware:org.springframework.beans.factory.support.DefaultListableBeanFactory@5b4686b4: defining beans ...未完

5.2、初始化

Bean的初始化方法有三种方式,按照先后顺序是,@PostConstruct、afterPropertiesSet、init-method

5.2.1 @PostConstruct

这个注解隐藏的比较深,它是在CommonAnnotationBeanPostProcessor的父类InitDestroyAnnotationBeanPostProcessor调用到的。这个注解的初始化方法不支持带参数,会直接抛异常。

if (method.getParameterTypes().length != 0) {
    throw new IllegalStateException("Lifecycle method annotation requires a no-arg method: " + method);
}
public void invoke(Object target) throws Throwable {
    ReflectionUtils.makeAccessible(this.method);
    this.method.invoke(target, (Object[]) null);
}
5.2.2 afterPropertiesSet

这个要实现InitializingBean接口。这个也不能有参数,因为它接口方法就没有定义参数。

    boolean isInitializingBean = (bean instanceof InitializingBean);
    if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
        if (logger.isDebugEnabled()) {
            logger.debug("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
        }
        ((InitializingBean) bean).afterPropertiesSet();
    }
5.2.3 init-method
ReflectionUtils.makeAccessible(initMethod);
initMethod.invoke(bean);

6、注册

registerDisposableBeanIfNecessary()完成Bean的缓存注册工作,把Bean注册到Map中。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,919评论 6 502
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,567评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,316评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,294评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,318评论 6 390
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,245评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,120评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,964评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,376评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,592评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,764评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,460评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,070评论 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,697评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,846评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,819评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,665评论 2 354

推荐阅读更多精彩内容