學習 Spring 的源碼,也可以通過 SpringBoot 搭環境。
不管是什么源碼,最好寫個 demo,跑起來,然后從常用的類和方法入手,跟蹤調試。
配置對象
新建一個 SpringBoot 的項目, 詳情見: https://blog.csdn.net/sinat_32502451/article/details/133039001
接著在 com.example.demo.model 路徑建一個類 Person,屬性包括 name和 age (也可以是其它的路徑,與以下的class路徑一致就行) 。
public class Person {private int age;private String name;public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}
}
然后在 resources 文件夾下,添加一個 mySpring.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="person" class= "com.example.demo.model.Person"><property name="name" value="Tom"/><property name="age" value="1"/></bean></beans>
查看配置的對象值:
創建一個類,查看 xml 配置的對象的值:
public class MySpring {public static void main(String[] args) {//可以在以下這段代碼打個斷點,跟蹤調試ApplicationContext context =new ClassPathXmlApplicationContext("classpath*:mySpring.xml");Person person = context.getBean("person", Person.class);System.out.println("=======>"+ person.getName());}}
在 ApplicationContext 開頭的這段代碼,打個斷點, 然后 跟蹤調試。
ClassPathXmlApplicationContext
從 xml 加載定義的 bean 對象,并且會通過 refresh 刷新 context 上下文 。
/*** Create a new ClassPathXmlApplicationContext with the given parent,* loading the definitions from the given XML files.* @param configLocations array of resource locations* @param refresh whether to automatically refresh the context,* loading all bean definitions and creating all singletons.* Alternatively, call refresh manually after further configuring the context.* @param parent the parent context* @throws BeansException if context creation failed* @see #refresh()*/public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)throws BeansException {super(parent);//設置配置文件的路徑setConfigLocations(configLocations);if (refresh) {//refresh()方法,負責初始化 ApplicationContext 容器。可以重點看看。refresh();}}
調試方法:
可以通過 Step Into 進入方法,也就是 Intellij Idea 的 F7 快捷鍵,繼續跟蹤。
Step Over ,也就是 Intellij Idea 的 F8 快捷鍵,單步調試,逐行調試。
遇到調用接口,如果不清楚是哪個接口實現類,可以直接在 Intellij Idea 的 接口上打斷點,調試時會自動跳轉到對應的接口實現類。
調試過程中,遇到不懂的,也可以百度搜索下。