本文將粗略的搭建一個Spring源碼的閱讀環境,為后面的源碼閱讀做一個准備。做任何事情不管是有一個完美的或者是不太完美的開頭,只要去做了,那么就是一種勝利。
由於spring使用了gradle構建工具,接下來先安裝gradle。
安裝gradle
- 從Gradle官網下載gradle安裝包,打開https://gradle.org/releases/
- 將下載的安裝包gradle-x.x.x-all.zip解壓到當前目錄
- 環境變量配置
- 配置GRADLE_HOME
- 配置Path
- 配置GRADLE_HOME
- 打開目錄行工具,輸入
gradle -v
,能看到gradle的版本信息表示安裝已經成功
導入Spring源碼
Spring在github上的倉庫地址是:https://github.com/spring-projects/spring-framework,本文不會直接去github上去下載源碼,網速實在太慢。本文使用的碼雲上Spring倉庫的鏡像,該鏡像每日同步一次,地址是https://gitee.com/mirrors/Spring-Framework
-
從git導入項目
-
填寫要克隆的git倉庫信息,可以點擊右邊的【Test】按鈕測試,等待倉庫克隆完成
-
打開導入的Spring項目
-
從gradle導入Spring項目,等待gradle build完成
注意:- 上面使用的是本地自己安裝的gradle。
- idea中gradle默認的服務目錄路徑是用戶目錄下的
.gradle
目錄,對於Administrator
用戶,對應的目錄是C:\Users\Administrator\.gradle
。該目錄占用的空間一般比較多,所以在這里將這個目錄放到其他的盤中。
-
構建完成后報錯如下(只列出了一部分):
...
Error:(63, 30) java: cannot find symbol
symbol: class Signature
location: class org.springframework.cglib.core.KeyFactory
...
location: class org.springframework.cglib.proxy.Enhancer
Error:(152, 30) java: cannot find symbol
...
spring未了避免與cglib和objenesis沖突,將cglib和objenesis相關的包重新repack到org.springframework.cglib
和org.springframework.objenesis
包中,這部分的代碼沒有包含到源碼當中。構建之前,可以通過添加Gradle任務來解決,見:https://github.com/spring-projects/spring-framework/blob/master/import-into-idea.md#known-issues和https://youtrack.jetbrains.com/issue/IDEA-160605
解決辦法如下:
- 在idea中打開Gradle面板
- 在右側的Gradle面板Spring -> Tasks -> other -> cglibRepackJar
- 激活任務
- 選擇要激活的cglibRepackJar任務
- 重新構建項目(花費的時間較長)
創建測試模塊my-test
為了方便編寫測試spring的代碼,在spring-framework單獨新建一個模塊my-test
-
右鍵spring-framework項目->New->Module...
-
輸入ArtifactId: my-test
-
一路下一步,最后點擊完成,新的模塊就建好了
-
添加依賴:
api(project(":spring-context"))
-
為了能讓my-test自動導入相關的依賴,在Gradle面板中右鍵spring節點
-
在my-test模塊中編寫程序測試
-
創建
MyApplication
package com.zfx; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MyApplication { public static void main(String[] args) { ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); Hello hello = (Hello)ac.getBean("hello"); hello.sayHello(); } }
-
在resources目錄下新建
applicationContext.xml
<?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="hello" class="com.zfx.Hello"></bean> </beans>
-
新建
Hello
類package com.zfx; public class Hello { public void sayHello() { System.out.println("Hello, zhangfengxian"); } }
-
運行
MyApplication
,可以看到控制台輸出:Hello, zhangfengxian
-
-
至此整個環境算是搭建好了
其他問題
spring-aspects
模塊構建時報錯
解決辦法一:排除spring-aspects
模塊
在工具欄點擊File -> Project Structure...
解決辦法二:使用Acj或者Eclipse編譯
在工具欄點擊File -> Settings...
此問題的相關鏈接:
- https://youtrack.jetbrains.com/issue/IDEA-64446
- https://www.jetbrains.com/help/idea/2016.2/using-the-aspectj-compiler-ajc.html