首页 > 技术文章 > Spring源码分析(二)容器基本用法

warehouse 2018-07-26 18:07 原文

摘要:本文结合《Spring源码深度解析》来分析Spring 5.0.6版本的源代码。若有描述错误之处,欢迎指正。

 

在正式分析Spring源码之前,我们有必要先来回顾一下Spring中最简单的用法。尽管我相信您已经对这个例子非常熟悉了。

Bean是Spring中最核心的概念,因为Spring就像是个大水桶,而Bean就像是水桶中的水,水桶脱离了水也就没什么用处了,那么我们先看看Bean的定义。

public class MySpringBean {
    private String str = "mySpringBean";

    public String getStr() {
        return str;
    }

    public void setStr(String str) {
        this.str = str;
    }
}

很普通,Bean没有任何特别之处。的确,Spring的目的就是让我们的Bean能成为一个纯粹的POJO,这也是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
                            http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="mySpringBean" class="org.cellphone.uc.MySpringBean"/>
</beans>

 

在上面的配置中我们看到了Bean的声明方式,接下来看测试代码:

public class BeanFactoryTest {

    @Test
    public void testSimpleLoad() {
        BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("spring/spring-test.xml"));
        MySpringBean bean = (MySpringBean) beanFactory.getBean("mySpringBean");
        Assert.assertEquals("testSimpleLoad", "mySpringBean", bean.getStr());
    }
}

XmlBeanFactory从Spring 3.1版本开始就被废弃了,但源码中未说明废弃的原因......

 

直接使用BeanFactory作为容器对于Spring的使用来说并不多见,因为在企业级的应用中大多数都会使用ApplicationContext(后续再介绍两者之间的差异),这里只是用于测试,让读者更快更好地分析Spring的内部原理。

通过上面一行简单的代码就拿到了MySpringBean实例,但这行代码在Spring中却执行了非常多的逻辑。接下来就来深入分析BeanFactory.getBean方法的实现原理。

 

推荐阅读