閱讀源碼第一步一定是要先把代碼跑起來,跑不起來的代碼就不用讀了。我認爲想要知道代碼的執行過程具體方法調用過程必須通過debug+斷點的方式纔是最合理也是最準確的。
秉着跑不起來的代碼不讀的原則,首先我們需要搭建一個demo幫助我們閱讀源碼。我習慣用IDEA作爲開發工具,所以這裏也是藉助IDEA閱讀springboot源碼。這裏簡便起見我直接使用IDEA的項目搭建工具Spring Initiallizr初始化一個springboot項目,過程比較簡單
初始化的項目結構
在IDEA的依賴管理中右鍵,選擇下載源碼
這樣我們就可以在跟蹤項目啓動過程中看代碼上的註釋
添加兩個測試類
package com.example.demo.controller;
import com.example.demo.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author Gensen.Lee
* @date 2020/7/1 11:21
*/
@RestController
public class TestController {
@Autowired
private TestService testService;
@GetMapping("/test")
public Object test(){
return testService.test();
}
}
package com.example.demo.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
/**
* @author Gensen.Lee
* @date 2020/7/1 11:18
*/
@Service
public class TestService {
@Autowired
ApplicationContext context;
public Object test(){
return context.getId();
}
}
application.properties配置文件中添加兩個基本信息
#應用名稱
spring.application.name=Demo project for Spring Boot
#啓動端口,默認8080
server.port=8080
啓動項目
瀏覽器打開地址http://localhost:8080/test
demo項目搭建完成