一筑煮、Spring源碼下載編譯
-
學(xué)習(xí)Spring源碼之前绿满,首先我們需要到GITHUB上下載Spring源碼:
image.png -
打開(kāi)IDEA編譯器構(gòu)建源碼臂外,Spring使用的Gradle構(gòu)建的:
image.png
構(gòu)建成功后
image.png
二、萬(wàn)事具備,接下來(lái)就要開(kāi)始我們的Spring源碼學(xué)習(xí)了B┙ :炕酢!本人也是第一次閱讀Spring源碼蔫浆,如果有錯(cuò)誤殖属,請(qǐng)各位包涵并指出
1.了解Spring 的 IOC 容器
1)創(chuàng)建測(cè)試類,方便我們對(duì)Spring源碼進(jìn)行Debug學(xué)習(xí)
image.png
-
新建module
image.png - 添加Gradle依賴
plugins {
id 'java'
}
group 'org.springframework'
version '5.3.0-SNAPSHOT'
repositories {
mavenCentral()
}
dependencies {
compile(project(":spring-beans"))
compile(project(":spring-core"))
testCompile group: 'junit', name: 'junit', version: '4.10'
}
- 新建實(shí)體類 MyBean
public class MyBean {
private String name = "我是MyBean";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
- 新建xml文件瓦盛,用來(lái)注冊(cè)bean
<?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="myBean" class="MyBean"/>
</beans>
- 新建測(cè)試類
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class SpringBeanFactoryStudyTest {
@Test
public void testXmLLoadBean(){
//通過(guò)XML配置文件獲取BeanFactory實(shí)例
BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("application-context.xml"));
//根據(jù)注冊(cè)Bean的名稱獲取類實(shí)例
MyBean bean = (MyBean) beanFactory.getBean("myBean");
System.out.println(bean.getName());
}
}
-
執(zhí)行結(jié)果
image.png
由此我們可以看出對(duì)象并不是有我們自己來(lái)創(chuàng)建的洗显,而是交給了Spring來(lái)進(jìn)行創(chuàng)建,創(chuàng)建對(duì)象的控制權(quán)由用戶反轉(zhuǎn)給了Spring原环,這就是簡(jiǎn)單的IOC控制反轉(zhuǎn)的一個(gè)例子挠唆。