摘要:本文結合《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方法的實現原理。